From 2cb0865343c4a2a26e46c8bd3970908c862d464e Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 27 Apr 2024 19:46:51 -0300 Subject: [PATCH] Add new fn safety enum for functions --- compiler/rustc_ast/src/ast.rs | 19 ++++++--- compiler/rustc_ast/src/mut_visit.rs | 15 +++++-- compiler/rustc_ast_lowering/src/delegation.rs | 4 +- compiler/rustc_ast_lowering/src/item.rs | 9 +++- compiler/rustc_ast_lowering/src/lib.rs | 2 +- .../rustc_ast_passes/src/ast_validation.rs | 10 ++--- compiler/rustc_ast_pretty/src/pprust/state.rs | 15 +++++-- .../src/diagnostics/region_errors.rs | 2 +- .../src/type_check/input_output.rs | 2 +- compiler/rustc_borrowck/src/type_check/mod.rs | 4 +- .../src/alloc_error_handler.rs | 4 +- .../src/global_allocator.rs | 4 +- compiler/rustc_builtin_macros/src/test.rs | 2 +- .../src/value_and_place.rs | 4 +- compiler/rustc_codegen_llvm/src/intrinsic.rs | 6 +-- .../rustc_codegen_ssa/src/codegen_attrs.rs | 2 +- .../src/debuginfo/type_names.rs | 2 +- .../src/const_eval/fn_queries.rs | 4 +- compiler/rustc_hir/src/hir.rs | 31 ++++++++++++-- .../rustc_hir_analysis/src/check/entry.rs | 4 +- .../rustc_hir_analysis/src/check/intrinsic.rs | 26 ++++++------ compiler/rustc_hir_analysis/src/check/mod.rs | 6 +-- compiler/rustc_hir_analysis/src/collect.rs | 27 +++++------- .../src/hir_ty_lowering/mod.rs | 15 ++----- compiler/rustc_hir_pretty/src/lib.rs | 17 +++++--- compiler/rustc_hir_typeck/src/callee.rs | 2 +- compiler/rustc_hir_typeck/src/check.rs | 6 +-- compiler/rustc_hir_typeck/src/closure.rs | 16 +++---- compiler/rustc_hir_typeck/src/coercion.rs | 42 +++++++++---------- compiler/rustc_hir_typeck/src/lib.rs | 2 +- compiler/rustc_hir_typeck/src/upvar.rs | 2 +- .../src/infer/error_reporting/mod.rs | 6 +-- .../infer/error_reporting/need_type_info.rs | 2 +- .../nice_region_error/placeholder_error.rs | 2 +- .../infer/error_reporting/note_and_explain.rs | 2 +- compiler/rustc_lint/src/builtin.rs | 2 +- compiler/rustc_lint/src/foreign_modules.rs | 4 +- compiler/rustc_middle/src/ty/adjustment.rs | 2 +- compiler/rustc_middle/src/ty/context.rs | 12 +++--- compiler/rustc_middle/src/ty/error.rs | 12 ++++-- compiler/rustc_middle/src/ty/fast_reject.rs | 4 +- compiler/rustc_middle/src/ty/print/pretty.rs | 2 +- compiler/rustc_middle/src/ty/relate.rs | 14 ++++++- .../rustc_middle/src/ty/structural_impls.rs | 5 ++- compiler/rustc_middle/src/ty/sty.rs | 16 +++---- compiler/rustc_middle/src/values.rs | 2 +- .../rustc_mir_build/src/check_unsafety.rs | 4 +- .../src/function_item_references.rs | 2 +- compiler/rustc_mir_transform/src/shim.rs | 2 +- compiler/rustc_parse/src/parser/item.rs | 16 +++---- compiler/rustc_parse/src/parser/mod.rs | 11 ++++- compiler/rustc_parse/src/parser/ty.rs | 4 +- compiler/rustc_passes/src/check_attr.rs | 4 +- .../rustc_smir/src/rustc_internal/internal.rs | 14 ++++++- .../rustc_smir/src/rustc_smir/convert/mod.rs | 10 +++++ .../rustc_smir/src/rustc_smir/convert/ty.rs | 6 +-- compiler/rustc_symbol_mangling/src/v0.rs | 2 +- .../error_reporting/on_unimplemented.rs | 6 +-- .../src/traits/error_reporting/suggestions.rs | 6 +-- .../src/traits/project.rs | 2 +- compiler/rustc_ty_utils/src/abi.rs | 10 ++--- compiler/stable_mir/src/mir/body.rs | 8 +++- compiler/stable_mir/src/ty.rs | 5 +-- 63 files changed, 299 insertions(+), 206 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index af246e3137187..6bee293a49318 100644 --- a/compiler/rustc_ast/src/ast.rs +++ b/compiler/rustc_ast/src/ast.rs @@ -2099,7 +2099,7 @@ impl Ty { #[derive(Clone, Encodable, Decodable, Debug)] pub struct BareFnTy { - pub unsafety: Unsafe, + pub safety: FnSafety, pub ext: Extern, pub generic_params: ThinVec, pub decl: P, @@ -2485,6 +2485,13 @@ pub enum Unsafe { No, } +#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] +#[derive(HashStable_Generic)] +pub enum FnSafety { + Unsafe(Span), + Default, +} + /// Describes what kind of coroutine markers, if any, a function has. /// /// Coroutine markers are things that cause the function to generate a coroutine, such as `async`, @@ -3001,8 +3008,8 @@ impl Extern { /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`). #[derive(Clone, Copy, Encodable, Decodable, Debug)] pub struct FnHeader { - /// The `unsafe` keyword, if any - pub unsafety: Unsafe, + /// The safety keyword, if any + pub safety: FnSafety, /// Whether this is `async`, `gen`, or nothing. pub coroutine_kind: Option, /// The `const` keyword, if any @@ -3014,8 +3021,8 @@ pub struct FnHeader { impl FnHeader { /// Does this function header have any qualifiers or is it empty? pub fn has_qualifiers(&self) -> bool { - let Self { unsafety, coroutine_kind, constness, ext } = self; - matches!(unsafety, Unsafe::Yes(_)) + let Self { safety, coroutine_kind, constness, ext } = self; + matches!(safety, FnSafety::Unsafe(_)) || coroutine_kind.is_some() || matches!(constness, Const::Yes(_)) || !matches!(ext, Extern::None) @@ -3025,7 +3032,7 @@ impl FnHeader { impl Default for FnHeader { fn default() -> FnHeader { FnHeader { - unsafety: Unsafe::No, + safety: FnSafety::Default, coroutine_kind: None, constness: Const::No, ext: Extern::None, diff --git a/compiler/rustc_ast/src/mut_visit.rs b/compiler/rustc_ast/src/mut_visit.rs index fc445600e77b9..272300ed393a8 100644 --- a/compiler/rustc_ast/src/mut_visit.rs +++ b/compiler/rustc_ast/src/mut_visit.rs @@ -499,8 +499,8 @@ pub fn noop_visit_ty(ty: &mut P, vis: &mut T) { vis.visit_mt(mt); } TyKind::BareFn(bft) => { - let BareFnTy { unsafety, ext: _, generic_params, decl, decl_span } = bft.deref_mut(); - visit_unsafety(unsafety, vis); + let BareFnTy { safety, ext: _, generic_params, decl, decl_span } = bft.deref_mut(); + visit_fn_safety(safety, vis); generic_params.flat_map_in_place(|param| vis.flat_map_generic_param(param)); vis.visit_fn_decl(decl); vis.visit_span(decl_span); @@ -864,6 +864,13 @@ fn visit_unsafety(unsafety: &mut Unsafe, vis: &mut T) { } } +fn visit_fn_safety(safety: &mut FnSafety, vis: &mut T) { + match safety { + FnSafety::Unsafe(span) => vis.visit_span(span), + FnSafety::Default => {} + } +} + // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. fn visit_polarity(polarity: &mut ImplPolarity, vis: &mut T) { match polarity { @@ -1226,10 +1233,10 @@ fn visit_const_item( } fn noop_visit_fn_header(header: &mut FnHeader, vis: &mut T) { - let FnHeader { unsafety, coroutine_kind, constness, ext: _ } = header; + let FnHeader { safety, coroutine_kind, constness, ext: _ } = header; visit_constness(constness, vis); coroutine_kind.as_mut().map(|coroutine_kind| vis.visit_coroutine_kind(coroutine_kind)); - visit_unsafety(unsafety, vis); + visit_fn_safety(safety, vis); } pub fn noop_visit_crate(krate: &mut Crate, vis: &mut T) { diff --git a/compiler/rustc_ast_lowering/src/delegation.rs b/compiler/rustc_ast_lowering/src/delegation.rs index a1e5c275c189c..4fc41e87031e1 100644 --- a/compiler/rustc_ast_lowering/src/delegation.rs +++ b/compiler/rustc_ast_lowering/src/delegation.rs @@ -188,7 +188,7 @@ impl<'hir> LoweringContext<'_, 'hir> { Asyncness::No => hir::IsAsync::NotAsync, }; hir::FnHeader { - unsafety: sig.unsafety, + safety: sig.safety, constness: self.tcx.constness(sig_id), asyncness, abi: sig.abi, @@ -341,7 +341,7 @@ impl<'hir> LoweringContext<'_, 'hir> { fn generate_header_error(&self) -> hir::FnHeader { hir::FnHeader { - unsafety: hir::Unsafety::Normal, + safety: hir::FnSafety::Default, constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, abi: abi::Abi::Rust, diff --git a/compiler/rustc_ast_lowering/src/item.rs b/compiler/rustc_ast_lowering/src/item.rs index dcce54d66c2d9..e1828a8df0904 100644 --- a/compiler/rustc_ast_lowering/src/item.rs +++ b/compiler/rustc_ast_lowering/src/item.rs @@ -1351,7 +1351,7 @@ impl<'hir> LoweringContext<'_, 'hir> { hir::IsAsync::NotAsync }; hir::FnHeader { - unsafety: self.lower_unsafety(h.unsafety), + safety: self.lower_fn_safety(h.safety), asyncness: asyncness, constness: self.lower_constness(h.constness), abi: self.lower_extern(h.ext), @@ -1408,6 +1408,13 @@ impl<'hir> LoweringContext<'_, 'hir> { } } + pub(super) fn lower_fn_safety(&mut self, u: FnSafety) -> hir::FnSafety { + match u { + FnSafety::Unsafe(_) => hir::FnSafety::Unsafe, + FnSafety::Default => hir::FnSafety::Default, + } + } + /// Return the pair of the lowered `generics` as `hir::Generics` and the evaluation of `f` with /// the carried impl trait definitions and bounds. #[instrument(level = "debug", skip(self, f))] diff --git a/compiler/rustc_ast_lowering/src/lib.rs b/compiler/rustc_ast_lowering/src/lib.rs index 61bc7f268cf47..5c7c28f780b67 100644 --- a/compiler/rustc_ast_lowering/src/lib.rs +++ b/compiler/rustc_ast_lowering/src/lib.rs @@ -1324,7 +1324,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> { let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params); hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy { generic_params, - unsafety: self.lower_unsafety(f.unsafety), + safety: self.lower_fn_safety(f.safety), abi: self.lower_extern(f.ext), decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None), param_names: self.lower_fn_params_to_names(&f.decl), diff --git a/compiler/rustc_ast_passes/src/ast_validation.rs b/compiler/rustc_ast_passes/src/ast_validation.rs index 1fb410253d1e7..d4f49827ded4e 100644 --- a/compiler/rustc_ast_passes/src/ast_validation.rs +++ b/compiler/rustc_ast_passes/src/ast_validation.rs @@ -521,7 +521,7 @@ impl<'a> AstValidator<'a> { fn check_foreign_fn_headerless( &self, // Deconstruct to ensure exhaustiveness - FnHeader { unsafety, coroutine_kind, constness, ext }: FnHeader, + FnHeader { safety, coroutine_kind, constness, ext }: FnHeader, ) { let report_err = |span| { self.dcx().emit_err(errors::FnQualifierInExtern { @@ -529,9 +529,9 @@ impl<'a> AstValidator<'a> { block: self.current_extern_span(), }); }; - match unsafety { - Unsafe::Yes(span) => report_err(span), - Unsafe::No => (), + match safety { + FnSafety::Unsafe(span) => report_err(span), + FnSafety::Default => (), } match coroutine_kind { Some(knd) => report_err(knd.span()), @@ -592,7 +592,7 @@ impl<'a> AstValidator<'a> { (Some(FnCtxt::Free), Some(header)) => match header.ext { Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _) | Extern::Implicit(_) - if matches!(header.unsafety, Unsafe::Yes(_)) => + if matches!(header.safety, FnSafety::Unsafe(_)) => { return; } diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 2c176828c841f..555db96d508d3 100644 --- a/compiler/rustc_ast_pretty/src/pprust/state.rs +++ b/compiler/rustc_ast_pretty/src/pprust/state.rs @@ -1138,7 +1138,7 @@ impl<'a> State<'a> { self.pclose(); } ast::TyKind::BareFn(f) => { - self.print_ty_fn(f.ext, f.unsafety, &f.decl, None, &f.generic_params); + self.print_ty_fn(f.ext, f.safety, &f.decl, None, &f.generic_params); } ast::TyKind::Path(None, path) => { self.print_path(path, false, 0); @@ -1892,7 +1892,7 @@ impl<'a> State<'a> { fn print_ty_fn( &mut self, ext: ast::Extern, - unsafety: ast::Unsafe, + safety: ast::FnSafety, decl: &ast::FnDecl, name: Option, generic_params: &[ast::GenericParam], @@ -1908,7 +1908,7 @@ impl<'a> State<'a> { }, span: DUMMY_SP, }; - let header = ast::FnHeader { unsafety, ext, ..ast::FnHeader::default() }; + let header = ast::FnHeader { safety, ext, ..ast::FnHeader::default() }; self.print_fn(decl, header, name, &generics); self.end(); } @@ -1916,7 +1916,7 @@ impl<'a> State<'a> { fn print_fn_header_info(&mut self, header: ast::FnHeader) { self.print_constness(header.constness); header.coroutine_kind.map(|coroutine_kind| self.print_coroutine_kind(coroutine_kind)); - self.print_unsafety(header.unsafety); + self.print_fn_safety(header.safety); match header.ext { ast::Extern::None => {} @@ -1940,6 +1940,13 @@ impl<'a> State<'a> { } } + fn print_fn_safety(&mut self, s: ast::FnSafety) { + match s { + ast::FnSafety::Default => {} + ast::FnSafety::Unsafe(_) => self.word_nbsp("unsafe"), + } + } + fn print_constness(&mut self, s: ast::Const) { match s { ast::Const::No => {} diff --git a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs index 2fe75fe2a2bff..91e8fda737d0a 100644 --- a/compiler/rustc_borrowck/src/diagnostics/region_errors.rs +++ b/compiler/rustc_borrowck/src/diagnostics/region_errors.rs @@ -1097,7 +1097,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> { liberated_sig.inputs().iter().copied(), peeled_ty, liberated_sig.c_variadic, - hir::Unsafety::Normal, + hir::FnSafety::Default, rustc_target::spec::abi::Abi::Rust, )), ); diff --git a/compiler/rustc_borrowck/src/type_check/input_output.rs b/compiler/rustc_borrowck/src/type_check/input_output.rs index 2511a1535af18..11005507d32f6 100644 --- a/compiler/rustc_borrowck/src/type_check/input_output.rs +++ b/compiler/rustc_borrowck/src/type_check/input_output.rs @@ -101,7 +101,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { user_provided_sig.inputs().iter().copied(), output_ty, user_provided_sig.c_variadic, - user_provided_sig.unsafety, + user_provided_sig.safety, user_provided_sig.abi, ); } diff --git a/compiler/rustc_borrowck/src/type_check/mod.rs b/compiler/rustc_borrowck/src/type_check/mod.rs index 61fa84666744b..154df1456a32e 100644 --- a/compiler/rustc_borrowck/src/type_check/mod.rs +++ b/compiler/rustc_borrowck/src/type_check/mod.rs @@ -2063,13 +2063,13 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> { } } - CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(unsafety)) => { + CastKind::PointerCoercion(PointerCoercion::ClosureFnPointer(safety)) => { let sig = match op.ty(body, tcx).kind() { ty::Closure(_, args) => args.as_closure().sig(), _ => bug!(), }; let ty_fn_ptr_from = - Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, *unsafety)); + Ty::new_fn_ptr(tcx, tcx.signature_unclosure(sig, *safety)); if let Err(terr) = self.eq_types( *ty, diff --git a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs index 064cf7d7f0f8e..66c4cd24528dc 100644 --- a/compiler/rustc_builtin_macros/src/alloc_error_handler.rs +++ b/compiler/rustc_builtin_macros/src/alloc_error_handler.rs @@ -3,7 +3,7 @@ use crate::util::check_builtin_macro_attribute; use rustc_ast::ptr::P; use rustc_ast::{self as ast, FnHeader, FnSig, Generics, StmtKind}; -use rustc_ast::{Fn, ItemKind, Stmt, TyKind, Unsafe}; +use rustc_ast::{Fn, FnSafety, ItemKind, Stmt, TyKind}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::Span; @@ -78,7 +78,7 @@ fn generate_handler(cx: &ExtCtxt<'_>, handler: Ident, span: Span, sig_span: Span let never = ast::FnRetTy::Ty(cx.ty(span, TyKind::Never)); let params = thin_vec![cx.param(span, size, ty_usize.clone()), cx.param(span, align, ty_usize)]; let decl = cx.fn_decl(params, never); - let header = FnHeader { unsafety: Unsafe::Yes(span), ..FnHeader::default() }; + let header = FnHeader { safety: FnSafety::Unsafe(span), ..FnHeader::default() }; let sig = FnSig { decl, header, span: span }; let body = Some(cx.block_expr(call)); diff --git a/compiler/rustc_builtin_macros/src/global_allocator.rs b/compiler/rustc_builtin_macros/src/global_allocator.rs index a1630ad1379e4..18f5115dd5185 100644 --- a/compiler/rustc_builtin_macros/src/global_allocator.rs +++ b/compiler/rustc_builtin_macros/src/global_allocator.rs @@ -6,7 +6,7 @@ use rustc_ast::expand::allocator::{ }; use rustc_ast::ptr::P; use rustc_ast::{self as ast, AttrVec, Expr, FnHeader, FnSig, Generics, Param, StmtKind}; -use rustc_ast::{Fn, ItemKind, Mutability, Stmt, Ty, TyKind, Unsafe}; +use rustc_ast::{Fn, FnSafety, ItemKind, Mutability, Stmt, Ty, TyKind}; use rustc_expand::base::{Annotatable, ExtCtxt}; use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::Span; @@ -73,7 +73,7 @@ impl AllocFnFactory<'_, '_> { let result = self.call_allocator(method.name, args); let output_ty = self.ret_ty(&method.output); let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty)); - let header = FnHeader { unsafety: Unsafe::Yes(self.span), ..FnHeader::default() }; + let header = FnHeader { safety: FnSafety::Unsafe(self.span), ..FnHeader::default() }; let sig = FnSig { decl, header, span: self.span }; let body = Some(self.cx.block_expr(result)); let kind = ItemKind::Fn(Box::new(Fn { diff --git a/compiler/rustc_builtin_macros/src/test.rs b/compiler/rustc_builtin_macros/src/test.rs index 134d5451b9c1c..1279154963e17 100644 --- a/compiler/rustc_builtin_macros/src/test.rs +++ b/compiler/rustc_builtin_macros/src/test.rs @@ -548,7 +548,7 @@ fn check_test_signature( let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic); let dcx = cx.dcx(); - if let ast::Unsafe::Yes(span) = f.sig.header.unsafety { + if let ast::FnSafety::Unsafe(span) = f.sig.header.safety { return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" })); } diff --git a/compiler/rustc_codegen_cranelift/src/value_and_place.rs b/compiler/rustc_codegen_cranelift/src/value_and_place.rs index dded6df7771df..844668ce56931 100644 --- a/compiler/rustc_codegen_cranelift/src/value_and_place.rs +++ b/compiler/rustc_codegen_cranelift/src/value_and_place.rs @@ -880,7 +880,7 @@ pub(crate) fn assert_assignable<'tcx>( let FnSig { inputs_and_output: types_from, c_variadic: c_variadic_from, - unsafety: unsafety_from, + safety: unsafety_from, abi: abi_from, } = from_sig; let to_sig = fx @@ -889,7 +889,7 @@ pub(crate) fn assert_assignable<'tcx>( let FnSig { inputs_and_output: types_to, c_variadic: c_variadic_to, - unsafety: unsafety_to, + safety: unsafety_to, abi: abi_to, } = to_sig; let mut types_from = types_from.iter(); diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 41347333ea6fe..7cb89fa315a1f 100644 --- a/compiler/rustc_codegen_llvm/src/intrinsic.rs +++ b/compiler/rustc_codegen_llvm/src/intrinsic.rs @@ -986,7 +986,7 @@ fn get_rust_try_fn<'ll, 'tcx>( [i8p], Ty::new_unit(tcx), false, - hir::Unsafety::Unsafe, + hir::FnSafety::Unsafe, Abi::Rust, )), ); @@ -997,7 +997,7 @@ fn get_rust_try_fn<'ll, 'tcx>( [i8p, i8p], Ty::new_unit(tcx), false, - hir::Unsafety::Unsafe, + hir::FnSafety::Unsafe, Abi::Rust, )), ); @@ -1006,7 +1006,7 @@ fn get_rust_try_fn<'ll, 'tcx>( [try_fn_ty, i8p, catch_fn_ty], tcx.types.i32, false, - hir::Unsafety::Unsafe, + hir::FnSafety::Unsafe, Abi::Rust, )); let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen); diff --git a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs index c28b0d644e675..69aa10f9b5b58 100644 --- a/compiler/rustc_codegen_ssa/src/codegen_attrs.rs +++ b/compiler/rustc_codegen_ssa/src/codegen_attrs.rs @@ -276,7 +276,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs { sym::target_feature => { if !tcx.is_closure_like(did.to_def_id()) && let Some(fn_sig) = fn_sig() - && fn_sig.skip_binder().unsafety() == hir::Unsafety::Normal + && fn_sig.skip_binder().safety() == hir::FnSafety::Default { if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc { // The `#[target_feature]` attribute is allowed on diff --git a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs index 5f0dcf9510f9d..8ac971da32722 100644 --- a/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs +++ b/compiler/rustc_codegen_ssa/src/debuginfo/type_names.rs @@ -364,7 +364,7 @@ fn push_debuginfo_type_name<'tcx>( } output.push_str(" (*)("); } else { - output.push_str(sig.unsafety.prefix_str()); + output.push_str(sig.safety.prefix_str()); if sig.abi != rustc_target::spec::abi::Abi::Rust { output.push_str("extern \""); diff --git a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs index ddad6683afbd9..18a41cf6a35fe 100644 --- a/compiler/rustc_const_eval/src/const_eval/fn_queries.rs +++ b/compiler/rustc_const_eval/src/const_eval/fn_queries.rs @@ -81,8 +81,8 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool { if cfg!(debug_assertions) && stab.promotable { let sig = tcx.fn_sig(def_id); assert_eq!( - sig.skip_binder().unsafety(), - hir::Unsafety::Normal, + sig.skip_binder().safety(), + hir::FnSafety::Default, "don't mark const unsafe fns as promotable", // https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682 ); diff --git a/compiler/rustc_hir/src/hir.rs b/compiler/rustc_hir/src/hir.rs index 1646ea50fb0f1..2fde83ec01063 100644 --- a/compiler/rustc_hir/src/hir.rs +++ b/compiler/rustc_hir/src/hir.rs @@ -2605,7 +2605,7 @@ impl PrimTy { #[derive(Debug, Clone, Copy, HashStable_Generic)] pub struct BareFnTy<'hir> { - pub unsafety: Unsafety, + pub safety: FnSafety, pub abi: Abi, pub generic_params: &'hir [GenericParam<'hir>], pub decl: &'hir FnDecl<'hir>, @@ -3204,6 +3204,31 @@ impl fmt::Display for Unsafety { } } +#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] +#[derive(Encodable, Decodable, HashStable_Generic)] +pub enum FnSafety { + Unsafe, + Default, +} + +impl FnSafety { + pub fn prefix_str(&self) -> &'static str { + match self { + Self::Unsafe => "unsafe ", + Self::Default => "", + } + } +} + +impl fmt::Display for FnSafety { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.write_str(match *self { + Self::Unsafe => "unsafe", + Self::Default => "normal", + }) + } +} + #[derive(Copy, Clone, PartialEq, Eq, Debug, Encodable, Decodable, HashStable_Generic)] pub enum Constness { Const, @@ -3221,7 +3246,7 @@ impl fmt::Display for Constness { #[derive(Copy, Clone, Debug, HashStable_Generic)] pub struct FnHeader { - pub unsafety: Unsafety, + pub safety: FnSafety, pub constness: Constness, pub asyncness: IsAsync, pub abi: Abi, @@ -3237,7 +3262,7 @@ impl FnHeader { } pub fn is_unsafe(&self) -> bool { - matches!(&self.unsafety, Unsafety::Unsafe) + matches!(&self.safety, FnSafety::Unsafe) } } diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index d5908cf285118..b5791dc7b844f 100644 --- a/compiler/rustc_hir_analysis/src/check/entry.rs +++ b/compiler/rustc_hir_analysis/src/check/entry.rs @@ -155,7 +155,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) { [], expected_return_type, false, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::Rust, )); @@ -251,7 +251,7 @@ fn check_start_fn_ty(tcx: TyCtxt<'_>, start_def_id: DefId) { [tcx.types.isize, Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8))], tcx.types.isize, false, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::Rust, )); diff --git a/compiler/rustc_hir_analysis/src/check/intrinsic.rs b/compiler/rustc_hir_analysis/src/check/intrinsic.rs index 74324c8695b80..e7691feffbb73 100644 --- a/compiler/rustc_hir_analysis/src/check/intrinsic.rs +++ b/compiler/rustc_hir_analysis/src/check/intrinsic.rs @@ -70,13 +70,13 @@ fn equate_intrinsic_type<'tcx>( } /// Returns the unsafety of the given intrinsic. -pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hir::Unsafety { +pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -> hir::FnSafety { let has_safe_attr = if tcx.has_attr(intrinsic_id, sym::rustc_intrinsic) { - tcx.fn_sig(intrinsic_id).skip_binder().unsafety() + tcx.fn_sig(intrinsic_id).skip_binder().safety() } else { match tcx.has_attr(intrinsic_id, sym::rustc_safe_intrinsic) { - true => hir::Unsafety::Normal, - false => hir::Unsafety::Unsafe, + true => hir::FnSafety::Default, + false => hir::FnSafety::Unsafe, } }; let is_in_list = match tcx.item_name(intrinsic_id.into()) { @@ -135,8 +135,8 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) - | sym::fmul_algebraic | sym::fdiv_algebraic | sym::frem_algebraic - | sym::const_eval_select => hir::Unsafety::Normal, - _ => hir::Unsafety::Unsafe, + | sym::const_eval_select => hir::FnSafety::Default, + _ => hir::FnSafety::Unsafe, }; if has_safe_attr != is_in_list { @@ -196,7 +196,7 @@ pub fn check_intrinsic_type( }) }; - let (n_tps, n_lts, n_cts, inputs, output, unsafety) = if name_str.starts_with("atomic_") { + let (n_tps, n_lts, n_cts, inputs, output, safety) = if name_str.starts_with("atomic_") { let split: Vec<&str> = name_str.split('_').collect(); assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format"); @@ -218,9 +218,9 @@ pub fn check_intrinsic_type( return; } }; - (n_tps, 0, 0, inputs, output, hir::Unsafety::Unsafe) + (n_tps, 0, 0, inputs, output, hir::FnSafety::Unsafe) } else { - let unsafety = intrinsic_operation_unsafety(tcx, intrinsic_id); + let safety = intrinsic_operation_unsafety(tcx, intrinsic_id); let (n_tps, n_cts, inputs, output) = match intrinsic_name { sym::abort => (0, 0, vec![], tcx.types.never), sym::unreachable => (0, 0, vec![], tcx.types.never), @@ -513,14 +513,14 @@ pub fn check_intrinsic_type( [mut_u8], Ty::new_unit(tcx), false, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::Rust, )); let catch_fn_ty = ty::Binder::dummy(tcx.mk_fn_sig( [mut_u8, mut_u8], Ty::new_unit(tcx), false, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::Rust, )); ( @@ -655,9 +655,9 @@ pub fn check_intrinsic_type( return; } }; - (n_tps, 0, n_cts, inputs, output, unsafety) + (n_tps, 0, n_cts, inputs, output, safety) }; - let sig = tcx.mk_fn_sig(inputs, output, false, unsafety, abi); + let sig = tcx.mk_fn_sig(inputs, output, false, safety, abi); let sig = ty::Binder::bind_with_vars(sig, bound_vars); equate_intrinsic_type(tcx, span, intrinsic_id, n_tps, n_lts, n_cts, sig) } diff --git a/compiler/rustc_hir_analysis/src/check/mod.rs b/compiler/rustc_hir_analysis/src/check/mod.rs index eb0ffc19d4540..93b0ee0aa52ca 100644 --- a/compiler/rustc_hir_analysis/src/check/mod.rs +++ b/compiler/rustc_hir_analysis/src/check/mod.rs @@ -454,7 +454,7 @@ fn fn_sig_suggestion<'tcx>( let output = if !output.is_unit() { format!(" -> {output}") } else { String::new() }; - let unsafety = sig.unsafety.prefix_str(); + let safety = sig.safety.prefix_str(); let (generics, where_clauses) = bounds_from_generic_predicates(tcx, predicates); // FIXME: this is not entirely correct, as the lifetimes from borrowed params will @@ -462,9 +462,7 @@ fn fn_sig_suggestion<'tcx>( // lifetimes between the `impl` and the `trait`, but this should be good enough to // fill in a significant portion of the missing code, and other subsequent // suggestions can help the user fix the code. - format!( - "{unsafety}{asyncness}fn {ident}{generics}({args}){output}{where_clauses} {{ todo!() }}" - ) + format!("{safety}{asyncness}fn {ident}{generics}({args}){output}{where_clauses} {{ todo!() }}") } /// Return placeholder code for the given associated item. diff --git a/compiler/rustc_hir_analysis/src/collect.rs b/compiler/rustc_hir_analysis/src/collect.rs index 0f0736f87568b..21fac72011b2b 100644 --- a/compiler/rustc_hir_analysis/src/collect.rs +++ b/compiler/rustc_hir_analysis/src/collect.rs @@ -1287,7 +1287,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder, def_id: LocalDefId) -> ty::EarlyBinder icx.lowerer().lower_fn_ty( - hir_id, - header.unsafety, - header.abi, - decl, - Some(generics), - None, - ), + }) => { + icx.lowerer().lower_fn_ty(hir_id, header.safety, header.abi, decl, Some(generics), None) + } ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => { let abi = tcx.hir().get_foreign_abi(hir_id); @@ -1322,8 +1317,8 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder hir::Unsafety::Normal, - _ => hir::Unsafety::Unsafe, + (Bound::Unbounded, Bound::Unbounded) => hir::FnSafety::Default, + _ => hir::FnSafety::Unsafe, }; ty::Binder::dummy(tcx.mk_fn_sig(inputs, ty, false, safety, abi::Abi::Rust)) } @@ -1410,13 +1405,13 @@ fn infer_return_ty_for_fn_sig<'tcx>( fn_sig.inputs().iter().copied(), recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)), fn_sig.c_variadic, - fn_sig.unsafety, + fn_sig.safety, fn_sig.abi, )) } None => icx.lowerer().lower_fn_ty( hir_id, - sig.header.unsafety, + sig.header.safety, sig.header.abi, sig.decl, Some(generics), @@ -1686,14 +1681,14 @@ fn compute_sig_of_foreign_fn_decl<'tcx>( decl: &'tcx hir::FnDecl<'tcx>, abi: abi::Abi, ) -> ty::PolyFnSig<'tcx> { - let unsafety = if abi == abi::Abi::RustIntrinsic { + let safety = if abi == abi::Abi::RustIntrinsic { intrinsic_operation_unsafety(tcx, def_id) } else { - hir::Unsafety::Unsafe + hir::FnSafety::Unsafe }; let hir_id = tcx.local_def_id_to_hir_id(def_id); let fty = - ItemCtxt::new(tcx, def_id).lowerer().lower_fn_ty(hir_id, unsafety, abi, decl, None, None); + ItemCtxt::new(tcx, def_id).lowerer().lower_fn_ty(hir_id, safety, abi, decl, None, None); // Feature gate SIMD types in FFI, since I am not sure that the // ABIs are handled at all correctly. -huonw diff --git a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs index 63da27246a2af..ab2eb5e92299a 100644 --- a/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs +++ b/compiler/rustc_hir_analysis/src/hir_ty_lowering/mod.rs @@ -2079,14 +2079,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { Ty::new_fn_ptr( tcx, - self.lower_fn_ty( - hir_ty.hir_id, - bf.unsafety, - bf.abi, - bf.decl, - None, - Some(hir_ty), - ), + self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)), ) } hir::TyKind::TraitObject(bounds, lifetime, repr) => { @@ -2308,11 +2301,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { } /// Lower a function type from the HIR to our internal notion of a function signature. - #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)] + #[instrument(level = "debug", skip(self, hir_id, safety, abi, decl, generics, hir_ty), ret)] pub fn lower_fn_ty( &self, hir_id: HirId, - unsafety: hir::Unsafety, + safety: hir::FnSafety, abi: abi::Abi, decl: &hir::FnDecl<'tcx>, generics: Option<&hir::Generics<'_>>, @@ -2375,7 +2368,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ { debug!(?output_ty); - let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi); + let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, safety, abi); let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars); if !self.allow_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) { diff --git a/compiler/rustc_hir_pretty/src/lib.rs b/compiler/rustc_hir_pretty/src/lib.rs index 285b99c2c69d5..b52e320fea523 100644 --- a/compiler/rustc_hir_pretty/src/lib.rs +++ b/compiler/rustc_hir_pretty/src/lib.rs @@ -283,7 +283,7 @@ impl<'a> State<'a> { self.pclose(); } hir::TyKind::BareFn(f) => { - self.print_ty_fn(f.abi, f.unsafety, f.decl, None, f.generic_params, f.param_names); + self.print_ty_fn(f.abi, f.safety, f.decl, None, f.generic_params, f.param_names); } hir::TyKind::OpaqueDef(..) => self.word("/*impl Trait*/"), hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false), @@ -347,7 +347,7 @@ impl<'a> State<'a> { self.print_fn( decl, hir::FnHeader { - unsafety: hir::Unsafety::Normal, + safety: hir::FnSafety::Default, constness: hir::Constness::NotConst, abi: Abi::Rust, asyncness: hir::IsAsync::NotAsync, @@ -2230,7 +2230,7 @@ impl<'a> State<'a> { fn print_ty_fn( &mut self, abi: Abi, - unsafety: hir::Unsafety, + safety: hir::FnSafety, decl: &hir::FnDecl<'_>, name: Option, generic_params: &[hir::GenericParam<'_>], @@ -2242,7 +2242,7 @@ impl<'a> State<'a> { self.print_fn( decl, hir::FnHeader { - unsafety, + safety, abi, constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, @@ -2263,7 +2263,7 @@ impl<'a> State<'a> { hir::IsAsync::Async(_) => self.word_nbsp("async"), } - self.print_unsafety(header.unsafety); + self.print_fn_safety(header.safety); if header.abi != Abi::Rust { self.word_nbsp("extern"); @@ -2287,6 +2287,13 @@ impl<'a> State<'a> { } } + fn print_fn_safety(&mut self, s: hir::FnSafety) { + match s { + hir::FnSafety::Default => {} + hir::FnSafety::Unsafe => self.word_nbsp("unsafe"), + } + } + fn print_is_auto(&mut self, s: hir::IsAuto) { match s { hir::IsAuto::Yes => self.word_nbsp("auto"), diff --git a/compiler/rustc_hir_typeck/src/callee.rs b/compiler/rustc_hir_typeck/src/callee.rs index dfd0b7c2945c4..b421fc11f8b57 100644 --- a/compiler/rustc_hir_typeck/src/callee.rs +++ b/compiler/rustc_hir_typeck/src/callee.rs @@ -198,7 +198,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { tupled_upvars_ty, ), coroutine_closure_sig.c_variadic, - coroutine_closure_sig.unsafety, + coroutine_closure_sig.safety, coroutine_closure_sig.abi, ); let adjustments = self.adjust_steps(autoderef); diff --git a/compiler/rustc_hir_typeck/src/check.rs b/compiler/rustc_hir_typeck/src/check.rs index b106eca59c473..094bb5b7c2d25 100644 --- a/compiler/rustc_hir_typeck/src/check.rs +++ b/compiler/rustc_hir_typeck/src/check.rs @@ -210,7 +210,7 @@ fn check_panic_info_fn(tcx: TyCtxt<'_>, fn_id: LocalDefId, fn_sig: ty::FnSig<'_> ty::BoundVariableKind::Region(ty::BrAnon), ]); let expected_sig = ty::Binder::bind_with_vars( - tcx.mk_fn_sig([panic_info_ref_ty], tcx.types.never, false, fn_sig.unsafety, Abi::Rust), + tcx.mk_fn_sig([panic_info_ref_ty], tcx.types.never, false, fn_sig.safety, Abi::Rust), bounds, ); @@ -233,7 +233,7 @@ fn check_lang_start_fn<'tcx>(tcx: TyCtxt<'tcx>, fn_sig: ty::FnSig<'tcx>, def_id: let generic_ty = Ty::new_param(tcx, fn_generic.index, fn_generic.name); let main_fn_ty = Ty::new_fn_ptr( tcx, - Binder::dummy(tcx.mk_fn_sig([], generic_ty, false, hir::Unsafety::Normal, Abi::Rust)), + Binder::dummy(tcx.mk_fn_sig([], generic_ty, false, hir::FnSafety::Default, Abi::Rust)), ); let expected_sig = ty::Binder::dummy(tcx.mk_fn_sig( @@ -245,7 +245,7 @@ fn check_lang_start_fn<'tcx>(tcx: TyCtxt<'tcx>, fn_sig: ty::FnSig<'tcx>, def_id: ], tcx.types.isize, false, - fn_sig.unsafety, + fn_sig.safety, Abi::Rust, )); diff --git a/compiler/rustc_hir_typeck/src/closure.rs b/compiler/rustc_hir_typeck/src/closure.rs index 4883c7aff8bc4..ad7a37d0b3b08 100644 --- a/compiler/rustc_hir_typeck/src/closure.rs +++ b/compiler/rustc_hir_typeck/src/closure.rs @@ -88,7 +88,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { [Ty::new_tup(tcx, sig.inputs())], sig.output(), sig.c_variadic, - sig.unsafety, + sig.safety, sig.abi, ) }); @@ -243,7 +243,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { ], Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]), sig.c_variadic, - sig.unsafety, + sig.safety, sig.abi, ) }), @@ -289,7 +289,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { liberated_sig.inputs().iter().copied(), coroutine_output_ty, liberated_sig.c_variadic, - liberated_sig.unsafety, + liberated_sig.safety, liberated_sig.abi, ); @@ -501,7 +501,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { input_tys, ret_param_ty, false, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::Rust, )); @@ -613,7 +613,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { sig.inputs().iter().cloned(), sig.output(), sig.c_variadic, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::RustCall, ) }); @@ -763,7 +763,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { inputs, supplied_output_ty, expected_sigs.liberated_sig.c_variadic, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::RustCall, ); @@ -840,7 +840,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { supplied_arguments, supplied_return, decl.c_variadic, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::RustCall, ), bound_vars, @@ -1004,7 +1004,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { supplied_arguments, err_ty, decl.c_variadic, - hir::Unsafety::Normal, + hir::FnSafety::Default, Abi::RustCall, )); diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 4165fa7f07d10..685647f0bb60f 100644 --- a/compiler/rustc_hir_typeck/src/coercion.rs +++ b/compiler/rustc_hir_typeck/src/coercion.rs @@ -816,8 +816,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { let outer_universe = self.infcx.universe(); let result = if let ty::FnPtr(fn_ty_b) = b.kind() - && let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) = - (fn_ty_a.unsafety(), fn_ty_b.unsafety()) + && let (hir::FnSafety::Default, hir::FnSafety::Unsafe) = + (fn_ty_a.safety(), fn_ty_b.safety()) { let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a); self.unify_and(unsafe_a, b, to_unsafe) @@ -879,7 +879,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396). - if b_sig.unsafety() == hir::Unsafety::Normal + if b_sig.safety() == hir::FnSafety::Default && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() { return Err(TypeError::TargetFeatureCast(def_id)); @@ -950,14 +950,14 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> { // or // `unsafe fn(arg0,arg1,...) -> _` let closure_sig = args_a.as_closure().sig(); - let unsafety = fn_ty.unsafety(); + let safety = fn_ty.safety(); let pointer_ty = - Ty::new_fn_ptr(self.tcx, self.tcx.signature_unclosure(closure_sig, unsafety)); + Ty::new_fn_ptr(self.tcx, self.tcx.signature_unclosure(closure_sig, safety)); debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty); self.unify_and( pointer_ty, b, - simple(Adjust::Pointer(PointerCoercion::ClosureFnPointer(unsafety))), + simple(Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety))), ) } _ => self.unify_and(a, b, identity), @@ -1154,27 +1154,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { (ty::Closure(_, args), ty::FnDef(..)) => { let b_sig = new_ty.fn_sig(self.tcx); let a_sig = - self.tcx.signature_unclosure(args.as_closure().sig(), b_sig.unsafety()); + self.tcx.signature_unclosure(args.as_closure().sig(), b_sig.safety()); (Some(a_sig), Some(b_sig)) } (ty::FnDef(..), ty::Closure(_, args)) => { let a_sig = prev_ty.fn_sig(self.tcx); let b_sig = - self.tcx.signature_unclosure(args.as_closure().sig(), a_sig.unsafety()); + self.tcx.signature_unclosure(args.as_closure().sig(), a_sig.safety()); (Some(a_sig), Some(b_sig)) } - (ty::Closure(_, args_a), ty::Closure(_, args_b)) => { - ( - Some(self.tcx.signature_unclosure( - args_a.as_closure().sig(), - hir::Unsafety::Normal, - )), - Some(self.tcx.signature_unclosure( - args_b.as_closure().sig(), - hir::Unsafety::Normal, - )), - ) - } + (ty::Closure(_, args_a), ty::Closure(_, args_b)) => ( + Some(self.tcx.signature_unclosure( + args_a.as_closure().sig(), + hir::FnSafety::Default, + )), + Some(self.tcx.signature_unclosure( + args_b.as_closure().sig(), + hir::FnSafety::Default, + )), + ), _ => (None, None), } } @@ -1196,14 +1194,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { let fn_ptr = Ty::new_fn_ptr(self.tcx, sig); let prev_adjustment = match prev_ty.kind() { ty::Closure(..) => { - Adjust::Pointer(PointerCoercion::ClosureFnPointer(a_sig.unsafety())) + Adjust::Pointer(PointerCoercion::ClosureFnPointer(a_sig.safety())) } ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer), _ => span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"), }; let next_adjustment = match new_ty.kind() { ty::Closure(..) => { - Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.unsafety())) + Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.safety())) } ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer), _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"), diff --git a/compiler/rustc_hir_typeck/src/lib.rs b/compiler/rustc_hir_typeck/src/lib.rs index 8bc070bcd36cd..3a9eac1b3e348 100644 --- a/compiler/rustc_hir_typeck/src/lib.rs +++ b/compiler/rustc_hir_typeck/src/lib.rs @@ -150,7 +150,7 @@ fn typeck_with_fallback<'tcx>( if let Some(hir::FnSig { header, decl, .. }) = node.fn_sig() { let fn_sig = if decl.output.get_infer_ret_ty().is_some() { - fcx.lowerer().lower_fn_ty(id, header.unsafety, header.abi, decl, None, None) + fcx.lowerer().lower_fn_ty(id, header.safety, header.abi, decl, None, None) } else { tcx.fn_sig(def_id).instantiate_identity() }; diff --git a/compiler/rustc_hir_typeck/src/upvar.rs b/compiler/rustc_hir_typeck/src/upvar.rs index 2bf4f51a8038a..8ff309d414546 100644 --- a/compiler/rustc_hir_typeck/src/upvar.rs +++ b/compiler/rustc_hir_typeck/src/upvar.rs @@ -421,7 +421,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { [], tupled_upvars_ty_for_borrow, false, - hir::Unsafety::Normal, + hir::FnSafety::Default, rustc_target::spec::abi::Abi::Rust, ), self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region( diff --git a/compiler/rustc_infer/src/infer/error_reporting/mod.rs b/compiler/rustc_infer/src/infer/error_reporting/mod.rs index 40a9db10956ea..cbadb73502351 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/mod.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/mod.rs @@ -1052,8 +1052,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { // unsafe extern "C" for<'a> fn(&'a T) -> &'a T // ^^^^^^ - values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety); - values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety); + values.0.push(sig1.safety.prefix_str(), sig1.safety != sig2.safety); + values.1.push(sig2.safety.prefix_str(), sig1.safety != sig2.safety); // unsafe extern "C" for<'a> fn(&'a T) -> &'a T // ^^^^^^^^^^ @@ -1927,7 +1927,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { self.tcx .signature_unclosure( args.as_closure().sig(), - rustc_hir::Unsafety::Normal, + rustc_hir::FnSafety::Default, ) .to_string(), ), diff --git a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs index a2a38d1c507a1..47bb3efb6b5e3 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/need_type_info.rs @@ -168,7 +168,7 @@ impl<'tcx> TypeFolder> for ClosureEraser<'tcx> { let closure_sig = args.as_closure().sig(); Ty::new_fn_ptr( self.tcx, - self.tcx.signature_unclosure(closure_sig, hir::Unsafety::Normal), + self.tcx.signature_unclosure(closure_sig, hir::FnSafety::Default), ) } _ => ty.super_fold_with(self), diff --git a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs index 01e75d59f4dfe..0a72c91e1cb0a 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/nice_region_error/placeholder_error.rs @@ -409,7 +409,7 @@ impl<'tcx> NiceRegionError<'_, 'tcx> { if let ty::Closure(_, args) = closure.kind() { self.tcx().signature_unclosure( args.as_closure().sig(), - rustc_hir::Unsafety::Normal, + rustc_hir::FnSafety::Default, ) } else { bug!("type is not longer closure"); diff --git a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs index 6a42f9b42c384..20e30fdb46061 100644 --- a/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs +++ b/compiler/rustc_infer/src/infer/error_reporting/note_and_explain.rs @@ -452,7 +452,7 @@ impl Trait for X { } (ty::FnPtr(sig), ty::FnDef(def_id, _)) | (ty::FnDef(def_id, _), ty::FnPtr(sig)) => { - if tcx.fn_sig(def_id).skip_binder().unsafety() < sig.unsafety() { + if tcx.fn_sig(def_id).skip_binder().safety() < sig.safety() { diag.note( "unsafe functions cannot be coerced into safe function pointers", ); diff --git a/compiler/rustc_lint/src/builtin.rs b/compiler/rustc_lint/src/builtin.rs index 0c89e186c47e3..ef8b475664ea6 100644 --- a/compiler/rustc_lint/src/builtin.rs +++ b/compiler/rustc_lint/src/builtin.rs @@ -416,7 +416,7 @@ impl EarlyLintPass for UnsafeCode { if let FnKind::Fn( ctxt, _, - ast::FnSig { header: ast::FnHeader { unsafety: ast::Unsafe::Yes(_), .. }, .. }, + ast::FnSig { header: ast::FnHeader { safety: ast::FnSafety::Unsafe(_), .. }, .. }, _, _, body, diff --git a/compiler/rustc_lint/src/foreign_modules.rs b/compiler/rustc_lint/src/foreign_modules.rs index fae492f252e5f..cded7d2746dd0 100644 --- a/compiler/rustc_lint/src/foreign_modules.rs +++ b/compiler/rustc_lint/src/foreign_modules.rs @@ -344,8 +344,8 @@ fn structurally_same_type_impl<'tcx>( let a_sig = tcx.instantiate_bound_regions_with_erased(a_poly_sig); let b_sig = tcx.instantiate_bound_regions_with_erased(b_poly_sig); - (a_sig.abi, a_sig.unsafety, a_sig.c_variadic) - == (b_sig.abi, b_sig.unsafety, b_sig.c_variadic) + (a_sig.abi, a_sig.safety, a_sig.c_variadic) + == (b_sig.abi, b_sig.safety, b_sig.c_variadic) && a_sig.inputs().iter().eq_by(b_sig.inputs().iter(), |a, b| { structurally_same_type_impl(seen_types, tcx, param_env, *a, *b, ckind) }) diff --git a/compiler/rustc_middle/src/ty/adjustment.rs b/compiler/rustc_middle/src/ty/adjustment.rs index c3e8991c63a20..1c8b6ed7c1885 100644 --- a/compiler/rustc_middle/src/ty/adjustment.rs +++ b/compiler/rustc_middle/src/ty/adjustment.rs @@ -15,7 +15,7 @@ pub enum PointerCoercion { /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer. /// It cannot convert a closure that requires unsafe. - ClosureFnPointer(hir::Unsafety), + ClosureFnPointer(hir::FnSafety), /// Go from a mut raw pointer to a const raw pointer. MutToConstPointer, diff --git a/compiler/rustc_middle/src/ty/context.rs b/compiler/rustc_middle/src/ty/context.rs index 45fa5e8f7ca38..61eff35298c20 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1945,10 +1945,10 @@ impl<'tcx> TyCtxt<'tcx> { /// that is, a `fn` type that is equivalent in every way for being /// unsafe. pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { - assert_eq!(sig.unsafety(), hir::Unsafety::Normal); + assert_eq!(sig.safety(), hir::FnSafety::Default); Ty::new_fn_ptr( self, - sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }), + sig.map_bound(|sig| ty::FnSig { safety: hir::FnSafety::Unsafe, ..sig }), ) } @@ -2012,14 +2012,14 @@ impl<'tcx> TyCtxt<'tcx> { pub fn signature_unclosure( self, sig: PolyFnSig<'tcx>, - unsafety: hir::Unsafety, + safety: hir::FnSafety, ) -> PolyFnSig<'tcx> { sig.map_bound(|s| { let params = match s.inputs()[0].kind() { ty::Tuple(params) => *params, _ => bug!(), }; - self.mk_fn_sig(params, s.output(), s.c_variadic, unsafety, abi::Abi::Rust) + self.mk_fn_sig(params, s.output(), s.c_variadic, safety, abi::Abi::Rust) }) } @@ -2286,7 +2286,7 @@ impl<'tcx> TyCtxt<'tcx> { inputs: I, output: I::Item, c_variadic: bool, - unsafety: hir::Unsafety, + safety: hir::FnSafety, abi: abi::Abi, ) -> T::Output where @@ -2296,7 +2296,7 @@ impl<'tcx> TyCtxt<'tcx> { T::collect_and_apply(inputs.into_iter().chain(iter::once(output)), |xs| ty::FnSig { inputs_and_output: self.mk_type_list(xs), c_variadic, - unsafety, + safety, abi, }) } diff --git a/compiler/rustc_middle/src/ty/error.rs b/compiler/rustc_middle/src/ty/error.rs index ce85c28ece89b..e20756fc877ae 100644 --- a/compiler/rustc_middle/src/ty/error.rs +++ b/compiler/rustc_middle/src/ty/error.rs @@ -34,6 +34,7 @@ pub enum TypeError<'tcx> { ConstnessMismatch(ExpectedFound), PolarityMismatch(ExpectedFound), UnsafetyMismatch(ExpectedFound), + FnSafetyMismatch(ExpectedFound), AbiMismatch(ExpectedFound), Mutability, ArgumentMutability(usize), @@ -109,6 +110,9 @@ impl<'tcx> TypeError<'tcx> { UnsafetyMismatch(values) => { format!("expected {} fn, found {} fn", values.expected, values.found).into() } + FnSafetyMismatch(values) => { + format!("expected {} fn, found {} fn", values.expected, values.found).into() + } AbiMismatch(values) => { format!("expected {} fn, found {} fn", values.expected, values.found).into() } @@ -203,10 +207,10 @@ impl<'tcx> TypeError<'tcx> { pub fn must_include_note(self) -> bool { use self::TypeError::*; match self { - CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_) - | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_) - | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_) - | VariadicMismatch(_) | TargetFeatureCast(_) => false, + CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | FnSafetyMismatch(_) + | ConstnessMismatch(_) | PolarityMismatch(_) | Mismatch | AbiMismatch(_) + | FixedArraySize(_) | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) + | FloatMismatch(_) | VariadicMismatch(_) | TargetFeatureCast(_) => false, Mutability | ArgumentMutability(_) diff --git a/compiler/rustc_middle/src/ty/fast_reject.rs b/compiler/rustc_middle/src/ty/fast_reject.rs index 10b0909209a05..2d07cf2e460b4 100644 --- a/compiler/rustc_middle/src/ty/fast_reject.rs +++ b/compiler/rustc_middle/src/ty/fast_reject.rs @@ -280,13 +280,13 @@ impl DeepRejectCtxt { } ty::FnPtr(obl_sig) => match k { ty::FnPtr(impl_sig) => { - let ty::FnSig { inputs_and_output, c_variadic, unsafety, abi } = + let ty::FnSig { inputs_and_output, c_variadic, safety, abi } = obl_sig.skip_binder(); let impl_sig = impl_sig.skip_binder(); abi == impl_sig.abi && c_variadic == impl_sig.c_variadic - && unsafety == impl_sig.unsafety + && safety == impl_sig.safety && inputs_and_output.len() == impl_sig.inputs_and_output.len() && iter::zip(inputs_and_output, impl_sig.inputs_and_output) .all(|(obl, imp)| self.types_may_unify(obl, imp)) diff --git a/compiler/rustc_middle/src/ty/print/pretty.rs b/compiler/rustc_middle/src/ty/print/pretty.rs index e5450182bf299..105dc0e5c80cc 100644 --- a/compiler/rustc_middle/src/ty/print/pretty.rs +++ b/compiler/rustc_middle/src/ty/print/pretty.rs @@ -3103,7 +3103,7 @@ define_print_and_forward_display! { } ty::FnSig<'tcx> { - p!(write("{}", self.unsafety.prefix_str())); + p!(write("{}", self.safety.prefix_str())); if self.abi != Abi::Rust { p!(write("extern {} ", self.abi)); diff --git a/compiler/rustc_middle/src/ty/relate.rs b/compiler/rustc_middle/src/ty/relate.rs index 3c1dea1d9f249..c45152968203b 100644 --- a/compiler/rustc_middle/src/ty/relate.rs +++ b/compiler/rustc_middle/src/ty/relate.rs @@ -144,7 +144,7 @@ impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> { if a.c_variadic != b.c_variadic { return Err(TypeError::VariadicMismatch(expected_found(a.c_variadic, b.c_variadic))); } - let unsafety = relation.relate(a.unsafety, b.unsafety)?; + let safety = relation.relate(a.safety, b.safety)?; let abi = relation.relate(a.abi, b.abi)?; if a.inputs().len() != b.inputs().len() { @@ -179,7 +179,7 @@ impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> { Ok(ty::FnSig { inputs_and_output: tcx.mk_type_list_from_iter(inputs_and_output)?, c_variadic: a.c_variadic, - unsafety, + safety, abi, }) } @@ -205,6 +205,16 @@ impl<'tcx> Relate<'tcx> for hir::Unsafety { } } +impl<'tcx> Relate<'tcx> for hir::FnSafety { + fn relate>( + _relation: &mut R, + a: hir::FnSafety, + b: hir::FnSafety, + ) -> RelateResult<'tcx, hir::FnSafety> { + if a != b { Err(TypeError::FnSafetyMismatch(expected_found(a, b))) } else { Ok(a) } + } +} + impl<'tcx> Relate<'tcx> for abi::Abi { fn relate>( _relation: &mut R, diff --git a/compiler/rustc_middle/src/ty/structural_impls.rs b/compiler/rustc_middle/src/ty/structural_impls.rs index 14a77d4b37ec7..c9aca6f8d0116 100644 --- a/compiler/rustc_middle/src/ty/structural_impls.rs +++ b/compiler/rustc_middle/src/ty/structural_impls.rs @@ -100,9 +100,9 @@ impl<'tcx> DebugWithInfcx> for ty::FnSig<'tcx> { f: &mut core::fmt::Formatter<'_>, ) -> core::fmt::Result { let sig = this.data; - let ty::FnSig { inputs_and_output: _, c_variadic, unsafety, abi } = sig; + let ty::FnSig { inputs_and_output: _, c_variadic, safety, abi } = sig; - write!(f, "{}", unsafety.prefix_str())?; + write!(f, "{}", safety.prefix_str())?; match abi { rustc_target::spec::abi::Abi::Rust => (), abi => write!(f, "extern \"{abi:?}\" ")?, @@ -464,6 +464,7 @@ TrivialTypeTraversalImpls! { TrivialTypeTraversalAndLiftImpls! { ::rustc_hir::def_id::DefId, ::rustc_hir::Unsafety, + ::rustc_hir::FnSafety, ::rustc_target::spec::abi::Abi, crate::ty::ClosureKind, crate::ty::ParamConst, diff --git a/compiler/rustc_middle/src/ty/sty.rs b/compiler/rustc_middle/src/ty/sty.rs index 0184ff5497952..fab047b89263a 100644 --- a/compiler/rustc_middle/src/ty/sty.rs +++ b/compiler/rustc_middle/src/ty/sty.rs @@ -390,7 +390,7 @@ impl<'tcx> CoroutineClosureArgs<'tcx> { yield_ty, return_ty, c_variadic: sig.c_variadic, - unsafety: sig.unsafety, + safety: sig.safety, abi: sig.abi, } }) @@ -418,8 +418,8 @@ pub struct CoroutineClosureSignature<'tcx> { // from scratch just for good measure. /// Always false pub c_variadic: bool, - /// Always [`hir::Unsafety::Normal`] - pub unsafety: hir::Unsafety, + /// Always [`hir::FnSafety::Default`] + pub safety: hir::FnSafety, /// Always [`abi::Abi::RustCall`] pub abi: abi::Abi, } @@ -1284,7 +1284,7 @@ pub struct GenSig<'tcx> { pub struct FnSig<'tcx> { pub inputs_and_output: &'tcx List>, pub c_variadic: bool, - pub unsafety: hir::Unsafety, + pub safety: hir::FnSafety, pub abi: abi::Abi, } @@ -1303,7 +1303,7 @@ impl<'tcx> FnSig<'tcx> { FnSig { inputs_and_output: List::empty(), c_variadic: false, - unsafety: hir::Unsafety::Normal, + safety: hir::FnSafety::Default, abi: abi::Abi::Rust, } } @@ -1337,8 +1337,8 @@ impl<'tcx> PolyFnSig<'tcx> { pub fn c_variadic(&self) -> bool { self.skip_binder().c_variadic } - pub fn unsafety(&self) -> hir::Unsafety { - self.skip_binder().unsafety + pub fn safety(&self) -> hir::FnSafety { + self.skip_binder().safety } pub fn abi(&self) -> abi::Abi { self.skip_binder().abi @@ -1348,7 +1348,7 @@ impl<'tcx> PolyFnSig<'tcx> { matches!( self.skip_binder(), ty::FnSig { - unsafety: rustc_hir::Unsafety::Normal, + safety: rustc_hir::FnSafety::Default, abi: Abi::Rust, c_variadic: false, .. diff --git a/compiler/rustc_middle/src/values.rs b/compiler/rustc_middle/src/values.rs index 5c17c0b3088fe..d22f4bef449ea 100644 --- a/compiler/rustc_middle/src/values.rs +++ b/compiler/rustc_middle/src/values.rs @@ -65,7 +65,7 @@ impl<'tcx> Value> for ty::Binder<'_, ty::FnSig<'_>> { std::iter::repeat(err).take(arity), err, false, - rustc_hir::Unsafety::Normal, + rustc_hir::FnSafety::Default, rustc_target::spec::abi::Abi::Rust, )); diff --git a/compiler/rustc_mir_build/src/check_unsafety.rs b/compiler/rustc_mir_build/src/check_unsafety.rs index 227d19c3e43c5..fab63bff3e5f8 100644 --- a/compiler/rustc_mir_build/src/check_unsafety.rs +++ b/compiler/rustc_mir_build/src/check_unsafety.rs @@ -390,7 +390,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> { return; // don't visit the whole expression } ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => { - if self.thir[fun].ty.fn_sig(self.tcx).unsafety() == hir::Unsafety::Unsafe { + if self.thir[fun].ty.fn_sig(self.tcx).safety() == hir::FnSafety::Unsafe { let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() { Some(*func_id) } else { @@ -920,7 +920,7 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) { 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| { - if fn_sig.header.unsafety == hir::Unsafety::Unsafe { + if fn_sig.header.safety == hir::FnSafety::Unsafe { SafetyContext::UnsafeFn } else { SafetyContext::Safe diff --git a/compiler/rustc_mir_transform/src/function_item_references.rs b/compiler/rustc_mir_transform/src/function_item_references.rs index 30b1ca6780062..434529ccff4bc 100644 --- a/compiler/rustc_mir_transform/src/function_item_references.rs +++ b/compiler/rustc_mir_transform/src/function_item_references.rs @@ -158,7 +158,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> { .lint_root; // FIXME: use existing printing routines to print the function signature let fn_sig = self.tcx.fn_sig(fn_id).instantiate(self.tcx, fn_args); - let unsafety = fn_sig.unsafety().prefix_str(); + let unsafety = fn_sig.safety().prefix_str(); let abi = match fn_sig.abi() { Abi::Rust => String::from(""), other_abi => { diff --git a/compiler/rustc_mir_transform/src/shim.rs b/compiler/rustc_mir_transform/src/shim.rs index 1c85a604053c7..b07ba523eddf9 100644 --- a/compiler/rustc_mir_transform/src/shim.rs +++ b/compiler/rustc_mir_transform/src/shim.rs @@ -1046,7 +1046,7 @@ fn build_construct_coroutine_by_move_shim<'tcx>( args.as_coroutine_closure().coroutine_captures_by_ref_ty(), ), sig.c_variadic, - sig.unsafety, + sig.safety, sig.abi, ) }); diff --git a/compiler/rustc_parse/src/parser/item.rs b/compiler/rustc_parse/src/parser/item.rs index ed51710564a42..81239f4f2e774 100644 --- a/compiler/rustc_parse/src/parser/item.rs +++ b/compiler/rustc_parse/src/parser/item.rs @@ -2435,7 +2435,7 @@ impl<'a> Parser<'a> { let coroutine_kind = self.parse_coroutine_kind(case); let unsafe_start_sp = self.token.span; - let unsafety = self.parse_unsafety(case); + let safety = self.parse_fn_safety(case); let ext_start_sp = self.token.span; let ext = self.parse_extern(case); @@ -2473,7 +2473,7 @@ impl<'a> Parser<'a> { // We may be able to recover let mut recover_constness = constness; let mut recover_coroutine_kind = coroutine_kind; - let mut recover_unsafety = unsafety; + let mut recover_safety = safety; // This will allow the machine fix to directly place the keyword in the correct place or to indicate // that the keyword is already present and the second instance should be removed. let wrong_kw = if self.check_keyword(kw::Const) { @@ -2511,10 +2511,10 @@ impl<'a> Parser<'a> { } } } else if self.check_keyword(kw::Unsafe) { - match unsafety { - Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)), - Unsafe::No => { - recover_unsafety = Unsafe::Yes(self.token.span); + match safety { + FnSafety::Unsafe(sp) => Some(WrongKw::Duplicated(sp)), + FnSafety::Default => { + recover_safety = FnSafety::Unsafe(self.token.span); Some(WrongKw::Misplaced(ext_start_sp)) } } @@ -2599,7 +2599,7 @@ impl<'a> Parser<'a> { err.emit(); return Ok(FnHeader { constness: recover_constness, - unsafety: recover_unsafety, + safety: recover_safety, coroutine_kind: recover_coroutine_kind, ext, }); @@ -2610,7 +2610,7 @@ impl<'a> Parser<'a> { } } - Ok(FnHeader { constness, unsafety, coroutine_kind, ext }) + Ok(FnHeader { constness, safety, coroutine_kind, ext }) } /// Parses the parameter list and result type of a function declaration. diff --git a/compiler/rustc_parse/src/parser/mod.rs b/compiler/rustc_parse/src/parser/mod.rs index 7486da33b2173..fb361895bcee3 100644 --- a/compiler/rustc_parse/src/parser/mod.rs +++ b/compiler/rustc_parse/src/parser/mod.rs @@ -26,7 +26,7 @@ use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor}; use rustc_ast::util::case::Case; use rustc_ast::{ self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs, - Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, StrLit, Unsafe, Visibility, + Expr, ExprKind, Extern, FnSafety, HasAttrs, HasTokens, Mutability, StrLit, Unsafe, Visibility, VisibilityKind, DUMMY_NODE_ID, }; use rustc_ast_pretty::pprust; @@ -1221,6 +1221,15 @@ impl<'a> Parser<'a> { } } + /// Parses fn unsafety: `unsafe`, `safe` or nothing. + fn parse_fn_safety(&mut self, case: Case) -> FnSafety { + if self.eat_keyword_case(kw::Unsafe, case) { + FnSafety::Unsafe(self.prev_token.uninterpolated_span()) + } else { + FnSafety::Default + } + } + /// Parses constness: `const` or nothing. fn parse_constness(&mut self, case: Case) -> Const { self.parse_constness_(case, false) diff --git a/compiler/rustc_parse/src/parser/ty.rs b/compiler/rustc_parse/src/parser/ty.rs index 7096b201f847a..dc7a73af8d773 100644 --- a/compiler/rustc_parse/src/parser/ty.rs +++ b/compiler/rustc_parse/src/parser/ty.rs @@ -590,7 +590,7 @@ impl<'a> Parser<'a> { tokens: None, }; let span_start = self.token.span; - let ast::FnHeader { ext, unsafety, constness, coroutine_kind } = + let ast::FnHeader { ext, safety, constness, coroutine_kind } = self.parse_fn_front_matter(&inherited_vis, Case::Sensitive)?; if self.may_recover() && self.token.kind == TokenKind::Lt { self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?; @@ -608,7 +608,7 @@ impl<'a> Parser<'a> { } // FIXME(gen_blocks): emit a similar error for `gen fn()` let decl_span = span_start.to(self.token.span); - Ok(TyKind::BareFn(P(BareFnTy { ext, unsafety, generic_params: params, decl, decl_span }))) + Ok(TyKind::BareFn(P(BareFnTy { ext, safety, generic_params: params, decl, decl_span }))) } /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`). diff --git a/compiler/rustc_passes/src/check_attr.rs b/compiler/rustc_passes/src/check_attr.rs index a2388b3bd5227..5d101d8b9d251 100644 --- a/compiler/rustc_passes/src/check_attr.rs +++ b/compiler/rustc_passes/src/check_attr.rs @@ -17,7 +17,7 @@ use rustc_hir::{self as hir}; use rustc_hir::{ self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, }; -use rustc_hir::{MethodKind, Target, Unsafety}; +use rustc_hir::{FnSafety, MethodKind, Target}; use rustc_macros::LintDiagnostic; use rustc_middle::hir::nested_filter; use rustc_middle::middle::resolve_bound_vars::ObjectLifetimeDefault; @@ -2334,7 +2334,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> { }), token_stream, false, - Unsafety::Normal, + FnSafety::Default, Abi::Rust, ); diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 0893bc31bfacd..f267f9579eaa5 100644 --- a/compiler/rustc_smir/src/rustc_internal/internal.rs +++ b/compiler/rustc_smir/src/rustc_internal/internal.rs @@ -10,7 +10,7 @@ use rustc_span::Symbol; use stable_mir::abi::Layout; use stable_mir::mir::alloc::AllocId; use stable_mir::mir::mono::{Instance, MonoItem, StaticDef}; -use stable_mir::mir::{BinOp, Mutability, Place, ProjectionElem, Safety}; +use stable_mir::mir::{BinOp, FnSafety, Mutability, Place, ProjectionElem, Safety}; use stable_mir::ty::{ Abi, AdtDef, Binder, BoundRegionKind, BoundTyKind, BoundVariableKind, ClosureKind, Const, DynKind, ExistentialPredicate, ExistentialProjection, ExistentialTraitRef, FloatTy, FnSig, @@ -216,7 +216,7 @@ impl RustcInternal for FnSig { tcx.lift(rustc_ty::FnSig { inputs_and_output: tcx.mk_type_list(&self.inputs_and_output.internal(tables, tcx)), c_variadic: self.c_variadic, - unsafety: self.unsafety.internal(tables, tcx), + safety: self.safety.internal(tables, tcx), abi: self.abi.internal(tables, tcx), }) .unwrap() @@ -491,6 +491,16 @@ impl RustcInternal for Safety { } } +impl RustcInternal for FnSafety { + type T<'tcx> = rustc_hir::FnSafety; + + fn internal<'tcx>(&self, _tables: &mut Tables<'_>, _tcx: TyCtxt<'tcx>) -> Self::T<'tcx> { + match self { + FnSafety::Unsafe => rustc_hir::FnSafety::Unsafe, + FnSafety::Default => rustc_hir::FnSafety::Default, + } + } +} impl RustcInternal for Span { type T<'tcx> = rustc_span::Span; diff --git a/compiler/rustc_smir/src/rustc_smir/convert/mod.rs b/compiler/rustc_smir/src/rustc_smir/convert/mod.rs index 41b0a84dd80f1..d20d2c5019082 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/mod.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/mod.rs @@ -19,6 +19,16 @@ impl<'tcx> Stable<'tcx> for rustc_hir::Unsafety { } } +impl<'tcx> Stable<'tcx> for rustc_hir::FnSafety { + type T = stable_mir::mir::FnSafety; + fn stable(&self, _: &mut Tables<'_>) -> Self::T { + match self { + rustc_hir::FnSafety::Unsafe => stable_mir::mir::FnSafety::Unsafe, + rustc_hir::FnSafety::Default => stable_mir::mir::FnSafety::Default, + } + } +} + impl<'tcx> Stable<'tcx> for FieldIdx { type T = usize; fn stable(&self, _: &mut Tables<'_>) -> Self::T { diff --git a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs index 4abf991fba25d..f9d56ac355307 100644 --- a/compiler/rustc_smir/src/rustc_smir/convert/ty.rs +++ b/compiler/rustc_smir/src/rustc_smir/convert/ty.rs @@ -104,8 +104,8 @@ impl<'tcx> Stable<'tcx> for ty::adjustment::PointerCoercion { match self { PointerCoercion::ReifyFnPointer => stable_mir::mir::PointerCoercion::ReifyFnPointer, PointerCoercion::UnsafeFnPointer => stable_mir::mir::PointerCoercion::UnsafeFnPointer, - PointerCoercion::ClosureFnPointer(unsafety) => { - stable_mir::mir::PointerCoercion::ClosureFnPointer(unsafety.stable(tables)) + PointerCoercion::ClosureFnPointer(safety) => { + stable_mir::mir::PointerCoercion::ClosureFnPointer(safety.stable(tables)) } PointerCoercion::MutToConstPointer => { stable_mir::mir::PointerCoercion::MutToConstPointer @@ -207,7 +207,7 @@ impl<'tcx> Stable<'tcx> for ty::FnSig<'tcx> { FnSig { inputs_and_output: self.inputs_and_output.iter().map(|ty| ty.stable(tables)).collect(), c_variadic: self.c_variadic, - unsafety: self.unsafety.stable(tables), + safety: self.safety.stable(tables), abi: self.abi.stable(tables), } } diff --git a/compiler/rustc_symbol_mangling/src/v0.rs b/compiler/rustc_symbol_mangling/src/v0.rs index 58b67c77a6150..f1b2e4866cc39 100644 --- a/compiler/rustc_symbol_mangling/src/v0.rs +++ b/compiler/rustc_symbol_mangling/src/v0.rs @@ -424,7 +424,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> { ty::FnPtr(sig) => { self.push("F"); self.in_binder(&sig, |cx, sig| { - if sig.unsafety == hir::Unsafety::Unsafe { + if sig.safety == hir::FnSafety::Unsafe { cx.push("U"); } match sig.abi { diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs index b418219fb957e..25c4458fa52fe 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/on_unimplemented.rs @@ -202,9 +202,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { if self_ty.is_fn() { let fn_sig = self_ty.fn_sig(self.tcx); - let shortname = match fn_sig.unsafety() { - hir::Unsafety::Normal => "fn", - hir::Unsafety::Unsafe => "unsafe fn", + let shortname = match fn_sig.safety() { + hir::FnSafety::Default => "fn", + hir::FnSafety::Unsafe => "unsafe fn", }; flags.push((sym::_Self, Some(shortname.to_owned()))); } diff --git a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs index d24942f3f46cd..c0a4aae1fc9a6 100644 --- a/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs +++ b/compiler/rustc_trait_selection/src/traits/error_reporting/suggestions.rs @@ -1895,7 +1895,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { infcx .next_ty_var(TypeVariableOrigin { span: DUMMY_SP, param_def_id: None }), false, - hir::Unsafety::Normal, + hir::FnSafety::Default, abi::Abi::Rust, ) } @@ -1903,7 +1903,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { [inputs], infcx.next_ty_var(TypeVariableOrigin { span: DUMMY_SP, param_def_id: None }), false, - hir::Unsafety::Normal, + hir::FnSafety::Default, abi::Abi::Rust, ), }; @@ -3928,7 +3928,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> { && let fn_sig @ ty::FnSig { abi: abi::Abi::Rust, c_variadic: false, - unsafety: hir::Unsafety::Normal, + safety: hir::FnSafety::Default, .. } = fn_ty.fn_sig(tcx).skip_binder() diff --git a/compiler/rustc_trait_selection/src/traits/project.rs b/compiler/rustc_trait_selection/src/traits/project.rs index 116e17c7e432f..3b68944ba4bc8 100644 --- a/compiler/rustc_trait_selection/src/traits/project.rs +++ b/compiler/rustc_trait_selection/src/traits/project.rs @@ -1688,7 +1688,7 @@ fn confirm_closure_candidate<'cx, 'tcx>( [sig.tupled_inputs_ty], output_ty, sig.c_variadic, - sig.unsafety, + sig.safety, sig.abi, ) }) diff --git a/compiler/rustc_ty_utils/src/abi.rs b/compiler/rustc_ty_utils/src/abi.rs index f0cea1f0baf38..9fa64bf4232fa 100644 --- a/compiler/rustc_ty_utils/src/abi.rs +++ b/compiler/rustc_ty_utils/src/abi.rs @@ -36,7 +36,7 @@ fn fn_sig_for_fn_abi<'tcx>( [], tcx.thread_local_ptr_ty(instance.def_id()), false, - hir::Unsafety::Normal, + hir::FnSafety::Default, rustc_target::spec::abi::Abi::Unadjusted, )); } @@ -95,7 +95,7 @@ fn fn_sig_for_fn_abi<'tcx>( iter::once(env_ty).chain(sig.inputs().iter().cloned()), sig.output(), sig.c_variadic, - sig.unsafety, + sig.safety, sig.abi, ), bound_vars, @@ -149,7 +149,7 @@ fn fn_sig_for_fn_abi<'tcx>( args.as_coroutine_closure().coroutine_captures_by_ref_ty(), ), sig.c_variadic, - sig.unsafety, + sig.safety, sig.abi, ), bound_vars, @@ -300,7 +300,7 @@ fn fn_sig_for_fn_abi<'tcx>( [env_ty, resume_ty], ret_ty, false, - hir::Unsafety::Normal, + hir::FnSafety::Default, rustc_target::spec::abi::Abi::Rust, ) } else { @@ -309,7 +309,7 @@ fn fn_sig_for_fn_abi<'tcx>( [env_ty], ret_ty, false, - hir::Unsafety::Normal, + hir::FnSafety::Default, rustc_target::spec::abi::Abi::Rust, ) }; diff --git a/compiler/stable_mir/src/mir/body.rs b/compiler/stable_mir/src/mir/body.rs index e077c58031806..dc632a059b28b 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -919,6 +919,12 @@ pub enum Safety { Normal, } +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum FnSafety { + Unsafe, + Default, +} + #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum PointerCoercion { /// Go from a fn-item type to a fn-pointer type. @@ -929,7 +935,7 @@ pub enum PointerCoercion { /// Go from a non-capturing closure to a fn pointer or an unsafe fn pointer. /// It cannot convert a closure that requires unsafe. - ClosureFnPointer(Safety), + ClosureFnPointer(FnSafety), /// Go from a mut raw pointer to a const raw pointer. MutToConstPointer, diff --git a/compiler/stable_mir/src/ty.rs b/compiler/stable_mir/src/ty.rs index bc6fb34493a6c..4cb8075b273de 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -1,6 +1,5 @@ use super::{ - mir::Safety, - mir::{Body, Mutability}, + mir::{Body, FnSafety, Mutability, Safety}, with, DefId, Error, Symbol, }; use crate::abi::Layout; @@ -903,7 +902,7 @@ pub type PolyFnSig = Binder; pub struct FnSig { pub inputs_and_output: Vec, pub c_variadic: bool, - pub unsafety: Safety, + pub safety: FnSafety, pub abi: Abi, }