Add hir::HeaderSafety to make follow up commits simpler

This commit is contained in:
Oli Scherer 2024-12-13 12:19:46 +00:00
parent e491caec14
commit a907c56a77
23 changed files with 101 additions and 40 deletions

View File

@ -198,7 +198,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
Asyncness::No => hir::IsAsync::NotAsync, Asyncness::No => hir::IsAsync::NotAsync,
}; };
hir::FnHeader { hir::FnHeader {
safety: sig.safety, safety: sig.safety.into(),
constness: self.tcx.constness(sig_id), constness: self.tcx.constness(sig_id),
asyncness, asyncness,
abi: sig.abi, abi: sig.abi,
@ -384,7 +384,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
fn generate_header_error(&self) -> hir::FnHeader { fn generate_header_error(&self) -> hir::FnHeader {
hir::FnHeader { hir::FnHeader {
safety: hir::Safety::Safe, safety: hir::Safety::Safe.into(),
constness: hir::Constness::NotConst, constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync, asyncness: hir::IsAsync::NotAsync,
abi: abi::Abi::Rust, abi: abi::Abi::Rust,

View File

@ -1358,8 +1358,12 @@ impl<'hir> LoweringContext<'_, 'hir> {
} else { } else {
hir::IsAsync::NotAsync hir::IsAsync::NotAsync
}; };
let safety = self.lower_safety(h.safety, default_safety);
let safety = safety.into();
hir::FnHeader { hir::FnHeader {
safety: self.lower_safety(h.safety, default_safety), safety,
asyncness, asyncness,
constness: self.lower_constness(h.constness), constness: self.lower_constness(h.constness),
abi: self.lower_extern(h.ext), abi: self.lower_extern(h.ext),

View File

@ -3762,9 +3762,20 @@ impl fmt::Display for Constness {
} }
} }
#[derive(Copy, Clone, Debug, HashStable_Generic, PartialEq, Eq)]
pub enum HeaderSafety {
Normal(Safety),
}
impl From<Safety> for HeaderSafety {
fn from(v: Safety) -> Self {
Self::Normal(v)
}
}
#[derive(Copy, Clone, Debug, HashStable_Generic)] #[derive(Copy, Clone, Debug, HashStable_Generic)]
pub struct FnHeader { pub struct FnHeader {
pub safety: Safety, pub safety: HeaderSafety,
pub constness: Constness, pub constness: Constness,
pub asyncness: IsAsync, pub asyncness: IsAsync,
pub abi: ExternAbi, pub abi: ExternAbi,
@ -3780,7 +3791,17 @@ impl FnHeader {
} }
pub fn is_unsafe(&self) -> bool { pub fn is_unsafe(&self) -> bool {
self.safety.is_unsafe() self.safety().is_unsafe()
}
pub fn is_safe(&self) -> bool {
self.safety().is_safe()
}
pub fn safety(&self) -> Safety {
match self.safety {
HeaderSafety::Normal(safety) => safety,
}
} }
} }

View File

@ -1336,7 +1336,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFn
{ {
icx.lowerer().lower_fn_ty( icx.lowerer().lower_fn_ty(
hir_id, hir_id,
sig.header.safety, sig.header.safety(),
sig.header.abi, sig.header.abi,
sig.decl, sig.decl,
Some(generics), Some(generics),
@ -1351,13 +1351,18 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<'_, ty::PolyFn
kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _), kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
generics, generics,
.. ..
}) => { }) => icx.lowerer().lower_fn_ty(
icx.lowerer().lower_fn_ty(hir_id, header.safety, header.abi, decl, Some(generics), None) hir_id,
} header.safety(),
header.abi,
decl,
Some(generics),
None,
),
ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => { ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(sig, _, _), .. }) => {
let abi = tcx.hir().get_foreign_abi(hir_id); let abi = tcx.hir().get_foreign_abi(hir_id);
compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety) compute_sig_of_foreign_fn_decl(tcx, def_id, sig.decl, abi, sig.header.safety())
} }
Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => { Ctor(data) | Variant(hir::Variant { data, .. }) if data.ctor().is_some() => {
@ -1405,7 +1410,7 @@ fn lower_fn_sig_recovering_infer_ret_ty<'tcx>(
icx.lowerer().lower_fn_ty( icx.lowerer().lower_fn_ty(
icx.tcx().local_def_id_to_hir_id(def_id), icx.tcx().local_def_id_to_hir_id(def_id),
sig.header.safety, sig.header.safety(),
sig.header.abi, sig.header.abi,
sig.decl, sig.decl,
Some(generics), Some(generics),

View File

@ -2407,7 +2407,7 @@ impl<'a> State<'a> {
self.print_fn( self.print_fn(
decl, decl,
hir::FnHeader { hir::FnHeader {
safety, safety: safety.into(),
abi, abi,
constness: hir::Constness::NotConst, constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync, asyncness: hir::IsAsync::NotAsync,
@ -2423,12 +2423,16 @@ impl<'a> State<'a> {
fn print_fn_header_info(&mut self, header: hir::FnHeader) { fn print_fn_header_info(&mut self, header: hir::FnHeader) {
self.print_constness(header.constness); self.print_constness(header.constness);
let safety = match header.safety {
hir::HeaderSafety::Normal(safety) => safety,
};
match header.asyncness { match header.asyncness {
hir::IsAsync::NotAsync => {} hir::IsAsync::NotAsync => {}
hir::IsAsync::Async(_) => self.word_nbsp("async"), hir::IsAsync::Async(_) => self.word_nbsp("async"),
} }
self.print_safety(header.safety); self.print_safety(safety);
if header.abi != ExternAbi::Rust { if header.abi != ExternAbi::Rust {
self.word_nbsp("extern"); self.word_nbsp("extern");

View File

@ -932,10 +932,11 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
return Err(TypeError::ForceInlineCast); return Err(TypeError::ForceInlineCast);
} }
// Safe `#[target_feature]` functions are not assignable to safe fn pointers // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396),
// (RFC 2396). // report a better error than a safety mismatch.
// FIXME(target_feature): do this inside `coerce_from_safe_fn`.
if b_hdr.safety.is_safe() if b_hdr.safety.is_safe()
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() && self.tcx.codegen_fn_attrs(def_id).safe_target_features
{ {
return Err(TypeError::TargetFeatureCast(def_id)); return Err(TypeError::TargetFeatureCast(def_id));
} }

View File

@ -139,7 +139,7 @@ fn typeck_with_fallback<'tcx>(
// type that has an infer in it, lower the type directly so that it'll // type that has an infer in it, lower the type directly so that it'll
// be correctly filled with infer. We'll use this inference to provide // be correctly filled with infer. We'll use this inference to provide
// a suggestion later on. // a suggestion later on.
fcx.lowerer().lower_fn_ty(id, header.safety, header.abi, decl, None, None) fcx.lowerer().lower_fn_ty(id, header.safety(), header.abi, decl, None, None)
} else { } else {
tcx.fn_sig(def_id).instantiate_identity() tcx.fn_sig(def_id).instantiate_identity()
}; };

View File

@ -30,6 +30,8 @@ pub struct CodegenFnAttrs {
/// features (only enabled features are supported right now). /// features (only enabled features are supported right now).
/// Implied target features have already been applied. /// Implied target features have already been applied.
pub target_features: Vec<TargetFeature>, pub target_features: Vec<TargetFeature>,
/// Whether the function was declared safe, but has target features
pub safe_target_features: bool,
/// The `#[linkage = "..."]` attribute on Rust-defined items and the value we found. /// The `#[linkage = "..."]` attribute on Rust-defined items and the value we found.
pub linkage: Option<Linkage>, pub linkage: Option<Linkage>,
/// The `#[linkage = "..."]` attribute on foreign items and the value we found. /// The `#[linkage = "..."]` attribute on foreign items and the value we found.
@ -150,6 +152,7 @@ impl CodegenFnAttrs {
link_name: None, link_name: None,
link_ordinal: None, link_ordinal: None,
target_features: vec![], target_features: vec![],
safe_target_features: false,
linkage: None, linkage: None,
import_linkage: None, import_linkage: None,
link_section: None, link_section: None,

View File

@ -222,6 +222,7 @@ pub struct DelegationFnSig {
pub param_count: usize, pub param_count: usize,
pub has_self: bool, pub has_self: bool,
pub c_variadic: bool, pub c_variadic: bool,
pub target_feature: bool,
} }
#[derive(Clone, Copy, Debug)] #[derive(Clone, Copy, Debug)]

View File

@ -478,19 +478,27 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
return; // don't visit the whole expression return; // don't visit the whole expression
} }
ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => { ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
if self.thir[fun].ty.fn_sig(self.tcx).safety().is_unsafe() { let fn_ty = self.thir[fun].ty;
let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() { let sig = fn_ty.fn_sig(self.tcx);
let (callee_features, safe_target_features): (&[_], _) = match fn_ty.kind() {
ty::FnDef(func_id, ..) => {
let cg_attrs = self.tcx.codegen_fn_attrs(func_id);
(&cg_attrs.target_features, cg_attrs.safe_target_features)
}
_ => (&[], false),
};
if sig.safety().is_unsafe() && !safe_target_features {
let func_id = if let ty::FnDef(func_id, _) = fn_ty.kind() {
Some(*func_id) Some(*func_id)
} else { } else {
None None
}; };
self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id)); self.requires_unsafe(expr.span, CallToUnsafeFunction(func_id));
} else if let &ty::FnDef(func_did, _) = self.thir[fun].ty.kind() { } else if let &ty::FnDef(func_did, _) = fn_ty.kind() {
// If the called function has target features the calling function hasn't, // If the called function has target features the calling function hasn't,
// the call requires `unsafe`. Don't check this on wasm // the call requires `unsafe`. Don't check this on wasm
// targets, though. For more information on wasm see the // targets, though. For more information on wasm see the
// is_like_wasm check in hir_analysis/src/collect.rs // is_like_wasm check in hir_analysis/src/collect.rs
let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
if !self.tcx.sess.target.options.is_like_wasm if !self.tcx.sess.target.options.is_like_wasm
&& !callee_features.iter().all(|feature| { && !callee_features.iter().all(|feature| {
self.body_target_features.iter().any(|f| f.name == feature.name) self.body_target_features.iter().any(|f| f.name == feature.name)
@ -1111,7 +1119,12 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
let hir_id = tcx.local_def_id_to_hir_id(def); let hir_id = tcx.local_def_id_to_hir_id(def);
let safety_context = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| { let safety_context = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
if fn_sig.header.safety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe } match fn_sig.header.safety {
hir::HeaderSafety::Normal(safety) => match safety {
hir::Safety::Unsafe => SafetyContext::UnsafeFn,
hir::Safety::Safe => SafetyContext::Safe,
},
}
}); });
let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features; let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features;
let mut warnings = Vec::new(); let mut warnings = Vec::new();

View File

@ -5019,12 +5019,13 @@ struct ItemInfoCollector<'a, 'ra, 'tcx> {
} }
impl ItemInfoCollector<'_, '_, '_> { impl ItemInfoCollector<'_, '_, '_> {
fn collect_fn_info(&mut self, sig: &FnSig, id: NodeId) { fn collect_fn_info(&mut self, sig: &FnSig, id: NodeId, attrs: &[Attribute]) {
let sig = DelegationFnSig { let sig = DelegationFnSig {
header: sig.header, header: sig.header,
param_count: sig.decl.inputs.len(), param_count: sig.decl.inputs.len(),
has_self: sig.decl.has_self(), has_self: sig.decl.has_self(),
c_variadic: sig.decl.c_variadic(), c_variadic: sig.decl.c_variadic(),
target_feature: attrs.iter().any(|attr| attr.has_name(sym::target_feature)),
}; };
self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig); self.r.delegation_fn_sigs.insert(self.r.local_def_id(id), sig);
} }
@ -5043,7 +5044,7 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
| ItemKind::Trait(box Trait { ref generics, .. }) | ItemKind::Trait(box Trait { ref generics, .. })
| ItemKind::TraitAlias(ref generics, _) => { | ItemKind::TraitAlias(ref generics, _) => {
if let ItemKind::Fn(box Fn { ref sig, .. }) = &item.kind { if let ItemKind::Fn(box Fn { ref sig, .. }) = &item.kind {
self.collect_fn_info(sig, item.id); self.collect_fn_info(sig, item.id, &item.attrs);
} }
let def_id = self.r.local_def_id(item.id); let def_id = self.r.local_def_id(item.id);
@ -5076,7 +5077,7 @@ impl<'ast> Visitor<'ast> for ItemInfoCollector<'_, '_, '_> {
fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) { fn visit_assoc_item(&mut self, item: &'ast AssocItem, ctxt: AssocCtxt) {
if let AssocItemKind::Fn(box Fn { ref sig, .. }) = &item.kind { if let AssocItemKind::Fn(box Fn { ref sig, .. }) = &item.kind {
self.collect_fn_info(sig, item.id); self.collect_fn_info(sig, item.id, &item.attrs);
} }
visit::walk_assoc_item(self, item, ctxt); visit::walk_assoc_item(self, item, ctxt);
} }

View File

@ -3094,7 +3094,7 @@ fn clean_maybe_renamed_foreign_item<'tcx>(
let kind = match item.kind { let kind = match item.kind {
hir::ForeignItemKind::Fn(sig, names, generics) => ForeignFunctionItem( hir::ForeignItemKind::Fn(sig, names, generics) => ForeignFunctionItem(
clean_function(cx, &sig, generics, FunctionArgs::Names(names)), clean_function(cx, &sig, generics, FunctionArgs::Names(names)),
sig.header.safety, sig.header.safety(),
), ),
hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem( hir::ForeignItemKind::Static(ty, mutability, safety) => ForeignStaticItem(
Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None }, Static { type_: Box::new(clean_ty(ty, cx)), mutability, expr: None },

View File

@ -668,7 +668,7 @@ impl Item {
ty::Asyncness::Yes => hir::IsAsync::Async(DUMMY_SP), ty::Asyncness::Yes => hir::IsAsync::Async(DUMMY_SP),
ty::Asyncness::No => hir::IsAsync::NotAsync, ty::Asyncness::No => hir::IsAsync::NotAsync,
}; };
hir::FnHeader { safety: sig.safety(), abi: sig.abi(), constness, asyncness } hir::FnHeader { safety: sig.safety().into(), abi: sig.abi(), constness, asyncness }
} }
let header = match self.kind { let header = match self.kind {
ItemKind::ForeignFunctionItem(_, safety) => { ItemKind::ForeignFunctionItem(_, safety) => {
@ -676,9 +676,9 @@ impl Item {
let abi = tcx.fn_sig(def_id).skip_binder().abi(); let abi = tcx.fn_sig(def_id).skip_binder().abi();
hir::FnHeader { hir::FnHeader {
safety: if abi == ExternAbi::RustIntrinsic { safety: if abi == ExternAbi::RustIntrinsic {
intrinsic_operation_unsafety(tcx, def_id.expect_local()) intrinsic_operation_unsafety(tcx, def_id.expect_local()).into()
} else { } else {
safety safety.into()
}, },
abi, abi,
constness: if tcx.is_const_fn(def_id) { constness: if tcx.is_const_fn(def_id) {

View File

@ -1637,6 +1637,14 @@ impl PrintWithSpace for hir::Safety {
} }
} }
impl PrintWithSpace for hir::HeaderSafety {
fn print_with_space(&self) -> &str {
match self {
hir::HeaderSafety::Normal(safety) => safety.print_with_space(),
}
}
}
impl PrintWithSpace for hir::IsAsync { impl PrintWithSpace for hir::IsAsync {
fn print_with_space(&self) -> &str { fn print_with_space(&self) -> &str {
match self { match self {

View File

@ -469,7 +469,7 @@ fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[cl
let unsafety_flag = match myitem.kind { let unsafety_flag = match myitem.kind {
clean::FunctionItem(_) | clean::ForeignFunctionItem(..) clean::FunctionItem(_) | clean::ForeignFunctionItem(..)
if myitem.fn_header(tcx).unwrap().safety.is_unsafe() => if myitem.fn_header(tcx).unwrap().is_unsafe() =>
{ {
"<sup title=\"unsafe function\">⚠</sup>" "<sup title=\"unsafe function\">⚠</sup>"
} }

View File

@ -419,7 +419,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
id: LocalDefId, id: LocalDefId,
) -> Self::Result { ) -> Self::Result {
if let Some(header) = kind.header() if let Some(header) = kind.header()
&& header.safety.is_unsafe() && header.is_unsafe()
{ {
ControlFlow::Break(()) ControlFlow::Break(())
} else { } else {

View File

@ -32,7 +32,7 @@ pub fn check(
} }
let span = cx.tcx.def_span(owner_id); let span = cx.tcx.def_span(owner_id);
match (headers.safety, sig.header.safety) { match (headers.safety, sig.header.safety()) {
(false, Safety::Unsafe) => span_lint( (false, Safety::Unsafe) => span_lint(
cx, cx,
MISSING_SAFETY_DOC, MISSING_SAFETY_DOC,

View File

@ -34,7 +34,7 @@ pub fn check_fn(cx: &LateContext<'_>, kind: FnKind<'_>, decl: &FnDecl<'_>, body:
ImplicitSelfKind::None => return, ImplicitSelfKind::None => return,
}; };
let name = if sig.header.safety.is_unsafe() { let name = if sig.header.is_unsafe() {
name.strip_suffix("_unchecked").unwrap_or(name) name.strip_suffix("_unchecked").unwrap_or(name)
} else { } else {
name name

View File

@ -20,8 +20,8 @@ pub(super) fn check_fn<'tcx>(
def_id: LocalDefId, def_id: LocalDefId,
) { ) {
let safety = match kind { let safety = match kind {
intravisit::FnKind::ItemFn(_, _, hir::FnHeader { safety, .. }) => safety, intravisit::FnKind::ItemFn(_, _, header) => header.safety(),
intravisit::FnKind::Method(_, sig) => sig.header.safety, intravisit::FnKind::Method(_, sig) => sig.header.safety(),
intravisit::FnKind::Closure => return, intravisit::FnKind::Closure => return,
}; };
@ -31,7 +31,7 @@ pub(super) fn check_fn<'tcx>(
pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) { pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
if let hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(eid)) = item.kind { if let hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(eid)) = item.kind {
let body = cx.tcx.hir().body(eid); let body = cx.tcx.hir().body(eid);
check_raw_ptr(cx, sig.header.safety, sig.decl, body, item.owner_id.def_id); check_raw_ptr(cx, sig.header.safety(), sig.decl, body, item.owner_id.def_id);
} }
} }

View File

@ -95,7 +95,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString {
if let ImplItemKind::Fn(ref signature, _) = impl_item.kind if let ImplItemKind::Fn(ref signature, _) = impl_item.kind
// #11201 // #11201
&& let header = signature.header && let header = signature.header
&& header.safety.is_safe() && header.is_safe()
&& header.abi == Abi::Rust && header.abi == Abi::Rust
&& impl_item.ident.name == sym::to_string && impl_item.ident.name == sym::to_string
&& let decl = signature.decl && let decl = signature.decl

View File

@ -5309,7 +5309,7 @@ fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExpr
} }
const FN_HEADER: hir::FnHeader = hir::FnHeader { const FN_HEADER: hir::FnHeader = hir::FnHeader {
safety: hir::Safety::Safe, safety: hir::HeaderSafety::Normal(hir::Safety::Safe),
constness: hir::Constness::NotConst, constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync, asyncness: hir::IsAsync::NotAsync,
abi: rustc_target::spec::abi::Abi::Rust, abi: rustc_target::spec::abi::Abi::Rust,

View File

@ -75,7 +75,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault {
if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind {
let name = impl_item.ident.name; let name = impl_item.ident.name;
let id = impl_item.owner_id; let id = impl_item.owner_id;
if sig.header.safety.is_unsafe() { if sig.header.is_unsafe() {
// can't be implemented for unsafe new // can't be implemented for unsafe new
return; return;
} }

View File

@ -541,7 +541,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio
.collect(); .collect();
if let Some(args) = args if let Some(args) = args
&& !args.is_empty() && !args.is_empty()
&& body.is_none_or(|body| sig.header.safety.is_unsafe() || contains_unsafe_block(cx, body.value)) && body.is_none_or(|body| sig.header.is_unsafe() || contains_unsafe_block(cx, body.value))
{ {
span_lint_and_then( span_lint_and_then(
cx, cx,