From 6b76cac6c826ed6ab0fce41450fd679b5460d3af Mon Sep 17 00:00:00 2001 From: Santiago Pastorino Date: Sat, 27 Apr 2024 19:46:51 -0300 Subject: [PATCH] Add new safety enum to be used in inner extern block items --- compiler/rustc_ast/src/ast.rs | 23 ++++++++++---- 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 +-- .../rustc_codegen_gcc/src/intrinsic/mod.rs | 12 +++---- 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 | 24 +++++++------- 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 | 19 ++++-------- 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 | 21 +++++-------- 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 ++- src/librustdoc/clean/mod.rs | 4 +-- src/librustdoc/clean/types.rs | 8 ++--- src/librustdoc/html/format.rs | 13 ++++++-- src/librustdoc/html/render/mod.rs | 8 ++--- src/librustdoc/html/render/print_item.rs | 10 +++--- src/librustdoc/json/conversions.rs | 4 +-- src/tools/clippy/clippy_lints/src/derive.rs | 4 +-- .../clippy_lints/src/doc/missing_headers.rs | 8 ++--- .../clippy/clippy_lints/src/eta_reduction.rs | 10 +++--- .../src/functions/misnamed_getters.rs | 4 +-- .../src/functions/not_unsafe_ptr_arg_deref.rs | 16 +++++----- .../clippy_lints/src/inherent_to_string.rs | 4 +-- .../clippy/clippy_lints/src/methods/mod.rs | 6 ++-- .../src/multiple_unsafe_ops_per_block.rs | 6 ++-- .../clippy_lints/src/new_without_default.rs | 2 +- src/tools/clippy/clippy_lints/src/ptr.rs | 10 +++--- .../clippy/clippy_utils/src/ast_utils.rs | 4 +-- .../clippy_utils/src/check_proc_macro.rs | 6 ++-- .../clippy/clippy_utils/src/hir_utils.rs | 2 +- src/tools/clippy/clippy_utils/src/ty.rs | 4 +-- src/tools/clippy/clippy_utils/src/visitors.rs | 10 +++--- src/tools/rustfmt/src/items.rs | 8 ++--- src/tools/rustfmt/src/types.rs | 2 +- src/tools/rustfmt/src/utils.rs | 8 +++++ .../gvn.fn_pointers.GVN.panic-abort.diff | 8 ++--- .../gvn.fn_pointers.GVN.panic-unwind.diff | 8 ++--- ...fg-pre-optimizations.after.panic-abort.mir | 2 +- ...g-pre-optimizations.after.panic-unwind.mir | 2 +- 92 files changed, 396 insertions(+), 300 deletions(-) diff --git a/compiler/rustc_ast/src/ast.rs b/compiler/rustc_ast/src/ast.rs index af246e3137187..acb99b39191b4 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: Safety, pub ext: Extern, pub generic_params: ThinVec, pub decl: P, @@ -2485,6 +2485,17 @@ pub enum Unsafe { No, } +/// Safety of items (for now only used on inner extern block items). +#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] +#[derive(HashStable_Generic)] +pub enum Safety { + /// `unsafe` an item is explicitly marked as `unsafe`. + Unsafe(Span), + /// Default means no value was provided, it will take a default value given the context in + /// which is used. + 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 +3012,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: Safety, /// Whether this is `async`, `gen`, or nothing. pub coroutine_kind: Option, /// The `const` keyword, if any @@ -3014,8 +3025,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, Safety::Unsafe(_)) || coroutine_kind.is_some() || matches!(constness, Const::Yes(_)) || !matches!(ext, Extern::None) @@ -3025,7 +3036,7 @@ impl FnHeader { impl Default for FnHeader { fn default() -> FnHeader { FnHeader { - unsafety: Unsafe::No, + safety: Safety::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..d5585560d88fc 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_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_safety(safety: &mut Safety, vis: &mut T) { + match safety { + Safety::Unsafe(span) => vis.visit_span(span), + Safety::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_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..1d9bfbe9b704c 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::Safety::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..fb3e221cb4e93 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_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_safety(&mut self, u: Safety) -> hir::Safety { + match u { + Safety::Unsafe(_) => hir::Safety::Unsafe, + Safety::Default => hir::Safety::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..1778d30c2a8b6 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_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..1c23bb39ed6ad 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 { + Safety::Unsafe(span) => report_err(span), + Safety::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, Safety::Unsafe(_)) => { return; } diff --git a/compiler/rustc_ast_pretty/src/pprust/state.rs b/compiler/rustc_ast_pretty/src/pprust/state.rs index 2c176828c841f..63410fca214ae 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::Safety, 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_safety(header.safety); match header.ext { ast::Extern::None => {} @@ -1940,6 +1940,13 @@ impl<'a> State<'a> { } } + fn print_safety(&mut self, s: ast::Safety) { + match s { + ast::Safety::Default => {} + ast::Safety::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..4862a286e7372 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::Safety::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..4721e74b9558b 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, ItemKind, Safety, 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: Safety::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..b44ff979303d1 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, ItemKind, Mutability, Safety, 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: Safety::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..4838128662986 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::Safety::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_gcc/src/intrinsic/mod.rs b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs index b7aec97ad8c27..a528eecc33bd3 100644 --- a/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs +++ b/compiler/rustc_codegen_gcc/src/intrinsic/mod.rs @@ -670,11 +670,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> { let step3 = self.or(left, right); // Fourth step. - if width == 8 { - step3 - } else { - self.gcc_bswap(step3, width) - } + if width == 8 { step3 } else { self.gcc_bswap(step3, width) } } 128 => { // TODO(antoyo): find a more efficient implementation? @@ -1225,7 +1221,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>( iter::once(i8p), Ty::new_unit(tcx), false, - rustc_hir::Unsafety::Unsafe, + rustc_hir::Safety::Unsafe, Abi::Rust, )), ); @@ -1236,7 +1232,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>( [i8p, i8p].iter().cloned(), Ty::new_unit(tcx), false, - rustc_hir::Unsafety::Unsafe, + rustc_hir::Safety::Unsafe, Abi::Rust, )), ); @@ -1245,7 +1241,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>( [try_fn_ty, i8p, catch_fn_ty], tcx.types.i32, false, - rustc_hir::Unsafety::Unsafe, + rustc_hir::Safety::Unsafe, Abi::Rust, )); let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen); diff --git a/compiler/rustc_codegen_llvm/src/intrinsic.rs b/compiler/rustc_codegen_llvm/src/intrinsic.rs index 41347333ea6fe..8de30f2d19f7e 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::Safety::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::Safety::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::Safety::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..9da32a7ec4310 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::Safety::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..256e9df328f18 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::Safety::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..88f7b457aeba2 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: Safety, 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 Safety { + Unsafe, + Default, +} + +impl Safety { + pub fn prefix_str(&self) -> &'static str { + match self { + Self::Unsafe => "unsafe ", + Self::Default => "", + } + } +} + +impl fmt::Display for Safety { + 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: Safety, 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, Safety::Unsafe) } } diff --git a/compiler/rustc_hir_analysis/src/check/entry.rs b/compiler/rustc_hir_analysis/src/check/entry.rs index d5908cf285118..2f65eed7bf261 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::Safety::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::Safety::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..ce530259b3e8a 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::Safety { 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::Safety::Default, + false => hir::Safety::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::Safety::Default, + _ => hir::Safety::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::Safety::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::Safety::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::Safety::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..599b22281aa67 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::Safety::Default, + _ => hir::Safety::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::Safety::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..30b0bf6a7f3f5 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::Safety, 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..f32d5d3120bb1 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::Safety::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::Safety, 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_safety(header.safety); if header.abi != Abi::Rust { self.word_nbsp("extern"); @@ -2287,6 +2287,13 @@ impl<'a> State<'a> { } } + fn print_safety(&mut self, s: hir::Safety) { + match s { + hir::Safety::Default => {} + hir::Safety::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..b6e13d7ad3188 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::Safety::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..9820d5f2f91e3 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::Safety::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::Safety::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::Safety::Default, Abi::RustCall, ); @@ -840,7 +840,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> { supplied_arguments, supplied_return, decl.c_variadic, - hir::Unsafety::Normal, + hir::Safety::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::Safety::Default, Abi::RustCall, )); diff --git a/compiler/rustc_hir_typeck/src/coercion.rs b/compiler/rustc_hir_typeck/src/coercion.rs index 4165fa7f07d10..2795992b44cf4 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::Safety::Default, hir::Safety::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::Safety::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,24 +1154,24 @@ 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, + hir::Safety::Default, )), Some(self.tcx.signature_unclosure( args_b.as_closure().sig(), - hir::Unsafety::Normal, + hir::Safety::Default, )), ) } @@ -1196,14 +1196,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..001d02de3f6b8 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::Safety::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..1b8141aa5c31e 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::Safety::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..649159b084e05 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::Safety::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..08c2dbc7f1e05 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::Safety::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..5e39c47f2a4ec 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::Safety::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..7fc0a786637d3 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::Safety), /// 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..2d5bc838e5cad 100644 --- a/compiler/rustc_middle/src/ty/context.rs +++ b/compiler/rustc_middle/src/ty/context.rs @@ -1945,11 +1945,8 @@ 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); - Ty::new_fn_ptr( - self, - sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }), - ) + assert_eq!(sig.safety(), hir::Safety::Default); + Ty::new_fn_ptr(self, sig.map_bound(|sig| ty::FnSig { safety: hir::Safety::Unsafe, ..sig })) } /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name` @@ -2009,17 +2006,13 @@ impl<'tcx> TyCtxt<'tcx> { /// `hir::Unsafety::Unsafe` in the previous example, then you would get /// an `unsafe fn (u32, i32)`. /// It cannot convert a closure that requires unsafe. - pub fn signature_unclosure( - self, - sig: PolyFnSig<'tcx>, - unsafety: hir::Unsafety, - ) -> PolyFnSig<'tcx> { + pub fn signature_unclosure(self, sig: PolyFnSig<'tcx>, safety: hir::Safety) -> 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 +2279,7 @@ impl<'tcx> TyCtxt<'tcx> { inputs: I, output: I::Item, c_variadic: bool, - unsafety: hir::Unsafety, + safety: hir::Safety, abi: abi::Abi, ) -> T::Output where @@ -2296,7 +2289,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..642ef177468bd 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), + SafetyMismatch(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() } + SafetyMismatch(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(_) | SafetyMismatch(_) + | 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..eb987bcb7c592 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::Safety { + fn relate>( + _relation: &mut R, + a: hir::Safety, + b: hir::Safety, + ) -> RelateResult<'tcx, hir::Safety> { + if a != b { Err(TypeError::SafetyMismatch(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..6eae29c329fbc 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::Safety, ::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..dd915088b3418 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::Safety::Default`] + pub safety: hir::Safety, /// 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::Safety, 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::Safety::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::Safety { + self.skip_binder().safety } pub fn abi(&self) -> abi::Abi { self.skip_binder().abi @@ -1347,12 +1347,7 @@ impl<'tcx> PolyFnSig<'tcx> { pub fn is_fn_trait_compatible(&self) -> bool { matches!( self.skip_binder(), - ty::FnSig { - unsafety: rustc_hir::Unsafety::Normal, - abi: Abi::Rust, - c_variadic: false, - .. - } + ty::FnSig { safety: rustc_hir::Safety::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..5fb87edf49ad7 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::Safety::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..304391399f0da 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::Safety::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::Safety::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..73a53068a1e1b 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_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 { + Safety::Unsafe(sp) => Some(WrongKw::Duplicated(sp)), + Safety::Default => { + recover_safety = Safety::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..fcf375c6f77a9 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, HasAttrs, HasTokens, Mutability, Safety, 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_safety(&mut self, case: Case) -> Safety { + if self.eat_keyword_case(kw::Unsafe, case) { + Safety::Unsafe(self.prev_token.uninterpolated_span()) + } else { + Safety::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..dee709553c3d1 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::{MethodKind, Safety, 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, + Safety::Default, Abi::Rust, ); diff --git a/compiler/rustc_smir/src/rustc_internal/internal.rs b/compiler/rustc_smir/src/rustc_internal/internal.rs index 9ad41d97c24b4..54972af85a631 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, Unsafe}; +use stable_mir::mir::{BinOp, Mutability, Place, ProjectionElem, Safety, Unsafe}; 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 Unsafe { } } +impl RustcInternal for Safety { + type T<'tcx> = rustc_hir::Safety; + + fn internal<'tcx>(&self, _tables: &mut Tables<'_>, _tcx: TyCtxt<'tcx>) -> Self::T<'tcx> { + match self { + Safety::Unsafe => rustc_hir::Safety::Unsafe, + Safety::Default => rustc_hir::Safety::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 4c04bfdfde16f..c00edde933e9f 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::Safety { + type T = stable_mir::mir::Safety; + fn stable(&self, _: &mut Tables<'_>) -> Self::T { + match self { + rustc_hir::Safety::Unsafe => stable_mir::mir::Safety::Unsafe, + rustc_hir::Safety::Default => stable_mir::mir::Safety::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..4d0ff222423c2 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::Safety::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..8b630c03ed6aa 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::Safety::Default => "fn", + hir::Safety::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..7820a9b48a011 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::Safety::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::Safety::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::Safety::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..330a1a6129559 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::Safety::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::Safety::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::Safety::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 0abc7294ff5a8..bbe00759e91d4 100644 --- a/compiler/stable_mir/src/mir/body.rs +++ b/compiler/stable_mir/src/mir/body.rs @@ -919,6 +919,12 @@ pub enum Unsafe { No, } +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum Safety { + 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(Unsafe), + ClosureFnPointer(Safety), /// 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 15bead0cf2454..9528d5ed22f06 100644 --- a/compiler/stable_mir/src/ty.rs +++ b/compiler/stable_mir/src/ty.rs @@ -1,6 +1,5 @@ use super::{ - mir::Unsafe, - mir::{Body, Mutability}, + mir::{Body, Mutability, Safety, Unsafe}, 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: Unsafe, + pub safety: Safety, pub abi: Abi, } diff --git a/src/librustdoc/clean/mod.rs b/src/librustdoc/clean/mod.rs index fc4f48262e5dc..38579aca44d95 100644 --- a/src/librustdoc/clean/mod.rs +++ b/src/librustdoc/clean/mod.rs @@ -2058,7 +2058,7 @@ pub(crate) fn clean_middle_ty<'tcx>( let generic_params = clean_bound_vars(sig.bound_vars()); BareFunction(Box::new(BareFunctionDecl { - unsafety: sig.unsafety(), + safety: sig.safety(), generic_params, decl, abi: sig.abi(), @@ -2541,7 +2541,7 @@ fn clean_bare_fn_ty<'tcx>( let decl = clean_fn_decl_with_args(cx, bare_fn.decl, None, args); (generic_params, decl) }); - BareFunctionDecl { unsafety: bare_fn.unsafety, abi: bare_fn.abi, decl, generic_params } + BareFunctionDecl { safety: bare_fn.safety, abi: bare_fn.abi, decl, generic_params } } pub(crate) fn reexport_chain<'tcx>( diff --git a/src/librustdoc/clean/types.rs b/src/librustdoc/clean/types.rs index af81cc6878e63..f51268321a4d2 100644 --- a/src/librustdoc/clean/types.rs +++ b/src/librustdoc/clean/types.rs @@ -636,17 +636,17 @@ impl Item { ty::Asyncness::Yes => hir::IsAsync::Async(DUMMY_SP), ty::Asyncness::No => hir::IsAsync::NotAsync, }; - hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness } + hir::FnHeader { safety: sig.safety(), abi: sig.abi(), constness, asyncness } } let header = match *self.kind { ItemKind::ForeignFunctionItem(_) => { let def_id = self.def_id().unwrap(); let abi = tcx.fn_sig(def_id).skip_binder().abi(); hir::FnHeader { - unsafety: if abi == Abi::RustIntrinsic { + safety: if abi == Abi::RustIntrinsic { intrinsic_operation_unsafety(tcx, def_id.expect_local()) } else { - hir::Unsafety::Unsafe + hir::Safety::Unsafe }, abi, constness: if abi == Abi::RustIntrinsic @@ -2344,7 +2344,7 @@ pub(crate) struct OpaqueTy { #[derive(Clone, PartialEq, Eq, Debug, Hash)] pub(crate) struct BareFunctionDecl { - pub(crate) unsafety: hir::Unsafety, + pub(crate) safety: hir::Safety, pub(crate) generic_params: Vec, pub(crate) decl: FnDecl, pub(crate) abi: Abi, diff --git a/src/librustdoc/html/format.rs b/src/librustdoc/html/format.rs index f82b89fdd5f98..7443babf64f54 100644 --- a/src/librustdoc/html/format.rs +++ b/src/librustdoc/html/format.rs @@ -1013,7 +1013,7 @@ fn fmt_type<'cx>( } clean::BareFunction(ref decl) => { print_higher_ranked_params_with_space(&decl.generic_params, cx).fmt(f)?; - decl.unsafety.print_with_space().fmt(f)?; + decl.safety.print_with_space().fmt(f)?; print_abi_with_space(decl.abi).fmt(f)?; if f.alternate() { f.write_str("fn")?; @@ -1303,7 +1303,7 @@ impl clean::Impl { // Link should match `# Trait implementations` print_higher_ranked_params_with_space(&bare_fn.generic_params, cx).fmt(f)?; - bare_fn.unsafety.print_with_space().fmt(f)?; + bare_fn.safety.print_with_space().fmt(f)?; print_abi_with_space(bare_fn.abi).fmt(f)?; let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" }; primitive_link_fragment( @@ -1613,6 +1613,15 @@ impl PrintWithSpace for hir::Unsafety { } } +impl PrintWithSpace for hir::Safety { + fn print_with_space(&self) -> &str { + match self { + hir::Safety::Unsafe => "unsafe ", + hir::Safety::Default => "", + } + } +} + impl PrintWithSpace for hir::IsAsync { fn print_with_space(&self) -> &str { match self { diff --git a/src/librustdoc/html/render/mod.rs b/src/librustdoc/html/render/mod.rs index 09a53affb14c0..f89f910b0b1e0 100644 --- a/src/librustdoc/html/render/mod.rs +++ b/src/librustdoc/html/render/mod.rs @@ -932,7 +932,7 @@ fn assoc_method( RenderMode::ForDeref { .. } => "", }; let asyncness = header.asyncness.print_with_space(); - let unsafety = header.unsafety.print_with_space(); + let safety = header.safety.print_with_space(); let abi = print_abi_with_space(header.abi).to_string(); let href = assoc_href_attr(meth, link, cx); @@ -943,7 +943,7 @@ fn assoc_method( + defaultness.len() + constness.len() + asyncness.len() - + unsafety.len() + + safety.len() + abi.len() + name.as_str().len() + generics_len; @@ -962,14 +962,14 @@ fn assoc_method( w.reserve(header_len + "{".len() + "".len()); write!( w, - "{indent}{vis}{defaultness}{constness}{asyncness}{unsafety}{abi}fn \ + "{indent}{vis}{defaultness}{constness}{asyncness}{safety}{abi}fn \ {name}{generics}{decl}{notable_traits}{where_clause}", indent = indent_str, vis = vis, defaultness = defaultness, constness = constness, asyncness = asyncness, - unsafety = unsafety, + safety = safety, abi = abi, href = href, name = name, diff --git a/src/librustdoc/html/render/print_item.rs b/src/librustdoc/html/render/print_item.rs index 7de2aea1c04b3..b5e3e3b893945 100644 --- a/src/librustdoc/html/render/print_item.rs +++ b/src/librustdoc/html/render/print_item.rs @@ -492,7 +492,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items: let unsafety_flag = match *myitem.kind { clean::FunctionItem(_) | clean::ForeignFunctionItem(_) - if myitem.fn_header(tcx).unwrap().unsafety == hir::Unsafety::Unsafe => + if myitem.fn_header(tcx).unwrap().safety == hir::Safety::Unsafe => { "" } @@ -616,7 +616,7 @@ fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &cle let tcx = cx.tcx(); let header = it.fn_header(tcx).expect("printing a function which isn't a function"); let constness = print_constness_with_space(&header.constness, it.const_stability(tcx)); - let unsafety = header.unsafety.print_with_space(); + let safety = header.safety.print_with_space(); let abi = print_abi_with_space(header.abi).to_string(); let asyncness = header.asyncness.print_with_space(); let visibility = visibility_print_with_space(it, cx).to_string(); @@ -627,7 +627,7 @@ fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &cle + visibility.len() + constness.len() + asyncness.len() - + unsafety.len() + + safety.len() + abi.len() + name.as_str().len() + generics_len; @@ -638,13 +638,13 @@ fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &cle w.reserve(header_len); write!( w, - "{attrs}{vis}{constness}{asyncness}{unsafety}{abi}fn \ + "{attrs}{vis}{constness}{asyncness}{safety}{abi}fn \ {name}{generics}{decl}{notable_traits}{where_clause}", attrs = render_attributes_in_pre(it, "", cx), vis = visibility, constness = constness, asyncness = asyncness, - unsafety = unsafety, + safety = safety, abi = abi, name = name, generics = f.generics.print(cx), diff --git a/src/librustdoc/json/conversions.rs b/src/librustdoc/json/conversions.rs index 35b99ab46f037..7f9d689fca77e 100644 --- a/src/librustdoc/json/conversions.rs +++ b/src/librustdoc/json/conversions.rs @@ -619,10 +619,10 @@ impl FromWithTcx for Term { impl FromWithTcx for FunctionPointer { fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self { - let clean::BareFunctionDecl { unsafety, generic_params, decl, abi } = bare_decl; + let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl; FunctionPointer { header: Header { - unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe), + unsafe_: matches!(safety, rustc_hir::Safety::Unsafe), const_: false, async_: false, abi: convert_abi(abi), diff --git a/src/tools/clippy/clippy_lints/src/derive.rs b/src/tools/clippy/clippy_lints/src/derive.rs index 42cd19fb8eca5..899ac7f957877 100644 --- a/src/tools/clippy/clippy_lints/src/derive.rs +++ b/src/tools/clippy/clippy_lints/src/derive.rs @@ -5,7 +5,7 @@ use rustc_errors::Applicability; use rustc_hir::def_id::DefId; use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, Visitor}; use rustc_hir::{ - self as hir, BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, Impl, Item, ItemKind, UnsafeSource, Unsafety, + self as hir, BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, Safety, Impl, Item, ItemKind, UnsafeSource, }; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::hir::nested_filter; @@ -415,7 +415,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> { } if let Some(header) = kind.header() - && header.unsafety == Unsafety::Unsafe + && header.safety == Safety::Unsafe { self.has_unsafe = true; } diff --git a/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs b/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs index f935ae2e3e489..600e6a04e646a 100644 --- a/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs +++ b/src/tools/clippy/clippy_lints/src/doc/missing_headers.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::{span_lint, span_lint_and_note}; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use clippy_utils::{is_doc_hidden, return_ty}; -use rustc_hir::{BodyId, FnSig, OwnerId, Unsafety}; +use rustc_hir::{BodyId, Safety, FnSig, OwnerId}; use rustc_lint::LateContext; use rustc_middle::ty; use rustc_span::{sym, Span}; @@ -33,14 +33,14 @@ pub fn check( } let span = cx.tcx.def_span(owner_id); - match (headers.safety, sig.header.unsafety) { - (false, Unsafety::Unsafe) => span_lint( + match (headers.safety, sig.header.safety) { + (false, Safety::Unsafe) => span_lint( cx, MISSING_SAFETY_DOC, span, "unsafe function's docs miss `# Safety` section", ), - (true, Unsafety::Normal) => span_lint( + (true, Safety::Default) => span_lint( cx, UNNECESSARY_SAFETY_DOC, span, diff --git a/src/tools/clippy/clippy_lints/src/eta_reduction.rs b/src/tools/clippy/clippy_lints/src/eta_reduction.rs index 306a4a9e55c9d..437077afceabc 100644 --- a/src/tools/clippy/clippy_lints/src/eta_reduction.rs +++ b/src/tools/clippy/clippy_lints/src/eta_reduction.rs @@ -5,7 +5,7 @@ use clippy_utils::ty::type_diagnostic_name; use clippy_utils::usage::{local_used_after_expr, local_used_in}; use clippy_utils::{get_path_from_caller_to_method_type, is_adjusted, path_to_local, path_to_local_id}; use rustc_errors::Applicability; -use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, Param, PatKind, QPath, TyKind, Unsafety}; +use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, Safety, Param, PatKind, QPath, TyKind}; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::{LateContext, LateLintPass}; use rustc_middle::ty::{ @@ -146,7 +146,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { ty::FnPtr(sig) => sig.skip_binder(), ty::Closure(_, subs) => cx .tcx - .signature_unclosure(subs.as_closure().sig(), Unsafety::Normal) + .signature_unclosure(subs.as_closure().sig(), Safety::Default) .skip_binder(), _ => { if typeck.type_dependent_def_id(body.value.hir_id).is_some() @@ -154,7 +154,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction { && let output = typeck.expr_ty(body.value) && let ty::Tuple(tys) = *subs.type_at(1).kind() { - cx.tcx.mk_fn_sig(tys, output, false, Unsafety::Normal, Abi::Rust) + cx.tcx.mk_fn_sig(tys, output, false, Safety::Default, Abi::Rust) } else { return; } @@ -241,10 +241,10 @@ fn check_inputs( } fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure: ClosureArgs<'tcx>, call_sig: FnSig<'_>) -> bool { - call_sig.unsafety == Unsafety::Normal + call_sig.safety == Safety::Default && !has_late_bound_to_non_late_bound_regions( cx.tcx - .signature_unclosure(closure.sig(), Unsafety::Normal) + .signature_unclosure(closure.sig(), Safety::Default) .skip_binder(), call_sig, ) diff --git a/src/tools/clippy/clippy_lints/src/functions/misnamed_getters.rs b/src/tools/clippy/clippy_lints/src/functions/misnamed_getters.rs index 8ac17e17688d3..7729c556e1fc8 100644 --- a/src/tools/clippy/clippy_lints/src/functions/misnamed_getters.rs +++ b/src/tools/clippy/clippy_lints/src/functions/misnamed_getters.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::source::snippet; use rustc_errors::Applicability; use rustc_hir::intravisit::FnKind; -use rustc_hir::{Body, ExprKind, FnDecl, ImplicitSelfKind, Unsafety}; +use rustc_hir::{Body, ExprKind, FnDecl, Safety, ImplicitSelfKind}; use rustc_lint::LateContext; use rustc_middle::ty; use rustc_span::Span; @@ -34,7 +34,7 @@ pub fn check_fn(cx: &LateContext<'_>, kind: FnKind<'_>, decl: &FnDecl<'_>, body: ImplicitSelfKind::None => return, }; - let name = if sig.header.unsafety == Unsafety::Unsafe { + let name = if sig.header.safety == Safety::Unsafe { name.strip_suffix("_unchecked").unwrap_or(name) } else { name diff --git a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs index 995dd782cbbd1..4523a3e7e68f5 100644 --- a/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs +++ b/src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs @@ -19,30 +19,30 @@ pub(super) fn check_fn<'tcx>( body: &'tcx hir::Body<'tcx>, def_id: LocalDefId, ) { - let unsafety = match kind { - intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }) => unsafety, - intravisit::FnKind::Method(_, sig) => sig.header.unsafety, + let safety = match kind { + intravisit::FnKind::ItemFn(_, _, hir::FnHeader { safety, .. }) => safety, + intravisit::FnKind::Method(_, sig) => sig.header.safety, intravisit::FnKind::Closure => return, }; - check_raw_ptr(cx, unsafety, decl, body, def_id); + check_raw_ptr(cx, safety, decl, body, def_id); } 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 { let body = cx.tcx.hir().body(eid); - check_raw_ptr(cx, sig.header.unsafety, sig.decl, body, item.owner_id.def_id); + check_raw_ptr(cx, sig.header.safety, sig.decl, body, item.owner_id.def_id); } } fn check_raw_ptr<'tcx>( cx: &LateContext<'tcx>, - unsafety: hir::Unsafety, + safety: hir::Safety, decl: &'tcx hir::FnDecl<'tcx>, body: &'tcx hir::Body<'tcx>, def_id: LocalDefId, ) { - if unsafety == hir::Unsafety::Normal && cx.effective_visibilities.is_exported(def_id) { + if safety == hir::Safety::Default && cx.effective_visibilities.is_exported(def_id) { let raw_ptrs = iter_input_pats(decl, body) .filter_map(|arg| raw_ptr_arg(cx, arg)) .collect::(); @@ -58,7 +58,7 @@ fn check_raw_ptr<'tcx>( }, hir::ExprKind::MethodCall(_, recv, args, _) => { let def_id = typeck.type_dependent_def_id(e.hir_id).unwrap(); - if cx.tcx.fn_sig(def_id).skip_binder().skip_binder().unsafety == hir::Unsafety::Unsafe { + if cx.tcx.fn_sig(def_id).skip_binder().skip_binder().safety == hir::Safety::Unsafe { check_arg(cx, &raw_ptrs, recv); for arg in args { check_arg(cx, &raw_ptrs, arg); diff --git a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs index 157f610598478..b23c37168b007 100644 --- a/src/tools/clippy/clippy_lints/src/inherent_to_string.rs +++ b/src/tools/clippy/clippy_lints/src/inherent_to_string.rs @@ -1,7 +1,7 @@ use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::ty::{implements_trait, is_type_lang_item}; use clippy_utils::{return_ty, trait_ref_of_method}; -use rustc_hir::{GenericParamKind, ImplItem, ImplItemKind, LangItem, Unsafety}; +use rustc_hir::{Safety, GenericParamKind, ImplItem, ImplItemKind, LangItem}; use rustc_lint::{LateContext, LateLintPass}; use rustc_session::declare_lint_pass; use rustc_span::sym; @@ -99,7 +99,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString { if let ImplItemKind::Fn(ref signature, _) = impl_item.kind // #11201 && let header = signature.header - && header.unsafety == Unsafety::Normal + && header.safety == Safety::Default && header.abi == Abi::Rust && impl_item.ident.name == sym::to_string && let decl = signature.decl diff --git a/src/tools/clippy/clippy_lints/src/methods/mod.rs b/src/tools/clippy/clippy_lints/src/methods/mod.rs index 0939c02856429..fe1e648b73a9d 100644 --- a/src/tools/clippy/clippy_lints/src/methods/mod.rs +++ b/src/tools/clippy/clippy_lints/src/methods/mod.rs @@ -5033,7 +5033,7 @@ fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExpr } const FN_HEADER: hir::FnHeader = hir::FnHeader { - unsafety: hir::Unsafety::Normal, + safety: hir::Safety::Default, constness: hir::Constness::NotConst, asyncness: hir::IsAsync::NotAsync, abi: rustc_target::spec::abi::Abi::Rust, @@ -5209,7 +5209,5 @@ impl OutType { } fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool { - expected.constness == actual.constness - && expected.unsafety == actual.unsafety - && expected.asyncness == actual.asyncness + expected.constness == actual.constness && expected.safety == actual.safety && expected.asyncness == actual.asyncness } diff --git a/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs b/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs index 0e13806678059..5306205aed7e8 100644 --- a/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs +++ b/src/tools/clippy/clippy_lints/src/multiple_unsafe_ops_per_block.rs @@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then; use clippy_utils::visitors::{for_each_expr_with_closures, Descend, Visitable}; use core::ops::ControlFlow::Continue; use hir::def::{DefKind, Res}; -use hir::{BlockCheckMode, ExprKind, QPath, UnOp, Unsafety}; +use hir::{BlockCheckMode, ExprKind, Safety, QPath, UnOp}; use rustc_ast::Mutability; use rustc_hir as hir; use rustc_lint::{LateContext, LateLintPass}; @@ -133,7 +133,7 @@ fn collect_unsafe_exprs<'tcx>( ty::FnPtr(sig) => sig, _ => return Continue(Descend::Yes), }; - if sig.unsafety() == Unsafety::Unsafe { + if sig.safety() == Safety::Unsafe { unsafe_ops.push(("unsafe function call occurs here", expr.span)); } }, @@ -144,7 +144,7 @@ fn collect_unsafe_exprs<'tcx>( .type_dependent_def_id(expr.hir_id) .map(|def_id| cx.tcx.fn_sig(def_id)) { - if sig.skip_binder().unsafety() == Unsafety::Unsafe { + if sig.skip_binder().safety() == Safety::Unsafe { unsafe_ops.push(("unsafe method call occurs here", expr.span)); } } diff --git a/src/tools/clippy/clippy_lints/src/new_without_default.rs b/src/tools/clippy/clippy_lints/src/new_without_default.rs index 78dd1e051627b..b60fea3f03e0e 100644 --- a/src/tools/clippy/clippy_lints/src/new_without_default.rs +++ b/src/tools/clippy/clippy_lints/src/new_without_default.rs @@ -75,7 +75,7 @@ impl<'tcx> LateLintPass<'tcx> for NewWithoutDefault { if let hir::ImplItemKind::Fn(ref sig, _) = impl_item.kind { let name = impl_item.ident.name; let id = impl_item.owner_id; - if sig.header.unsafety == hir::Unsafety::Unsafe { + if sig.header.safety == hir::Safety::Unsafe { // can't be implemented for unsafe new return; } diff --git a/src/tools/clippy/clippy_lints/src/ptr.rs b/src/tools/clippy/clippy_lints/src/ptr.rs index cc61ef9184cdc..fe66e381208f8 100644 --- a/src/tools/clippy/clippy_lints/src/ptr.rs +++ b/src/tools/clippy/clippy_lints/src/ptr.rs @@ -11,9 +11,9 @@ use rustc_hir::def_id::DefId; use rustc_hir::hir_id::{HirId, HirIdMap}; use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::{ - self as hir, AnonConst, BinOpKind, BindingMode, Body, Expr, ExprKind, FnRetTy, FnSig, GenericArg, + self as hir, AnonConst, BinOpKind, BindingMode, Body, Expr, ExprKind, FnRetTy, Safety, FnSig, GenericArg, ImplItemKind, ItemKind, Lifetime, Mutability, Node, Param, PatKind, QPath, TraitFn, TraitItem, TraitItemKind, - TyKind, Unsafety, + TyKind, }; use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::traits::{Obligation, ObligationCause}; @@ -543,7 +543,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio if let Some(args) = args && !args.is_empty() && body.map_or(true, |body| { - sig.header.unsafety == Unsafety::Unsafe || contains_unsafe_block(cx, body.value) + sig.header.safety == Safety::Unsafe || contains_unsafe_block(cx, body.value) }) { span_lint_and_then( @@ -687,9 +687,7 @@ fn check_ptr_arg_usage<'tcx>(cx: &LateContext<'tcx>, body: &'tcx Body<'_>, args: .filter_map(|(i, arg)| { let param = &body.params[arg.idx]; match param.pat.kind { - PatKind::Binding(BindingMode::NONE, id, _, None) - if !is_lint_allowed(cx, PTR_ARG, param.hir_id) => - { + PatKind::Binding(BindingMode::NONE, id, _, None) if !is_lint_allowed(cx, PTR_ARG, param.hir_id) => { Some((id, i)) }, _ => { diff --git a/src/tools/clippy/clippy_utils/src/ast_utils.rs b/src/tools/clippy/clippy_utils/src/ast_utils.rs index 0395eb1449b48..556f4defa8251 100644 --- a/src/tools/clippy/clippy_utils/src/ast_utils.rs +++ b/src/tools/clippy/clippy_utils/src/ast_utils.rs @@ -594,7 +594,7 @@ fn eq_opt_coroutine_kind(l: Option, r: Option) -> } pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool { - matches!(l.unsafety, Unsafe::No) == matches!(r.unsafety, Unsafe::No) + matches!(l.safety, Safety::Default) == matches!(r.safety, Safety::Default) && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind) && matches!(l.constness, Const::No) == matches!(r.constness, Const::No) && eq_ext(&l.ext, &r.ext) @@ -701,7 +701,7 @@ pub fn eq_ty(l: &Ty, r: &Ty) -> bool { both(ll, rl, |l, r| eq_id(l.ident, r.ident)) && l.mutbl == r.mutbl && eq_ty(&l.ty, &r.ty) }, (BareFn(l), BareFn(r)) => { - l.unsafety == r.unsafety + l.safety == r.safety && eq_ext(&l.ext, &r.ext) && over(&l.generic_params, &r.generic_params, eq_generic_param) && eq_fn_decl(&l.decl, &r.decl) diff --git a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs index 422673105136d..0919ea7d4d971 100644 --- a/src/tools/clippy/clippy_utils/src/check_proc_macro.rs +++ b/src/tools/clippy/clippy_utils/src/check_proc_macro.rs @@ -17,8 +17,8 @@ use rustc_ast::token::CommentKind; use rustc_ast::AttrStyle; use rustc_hir::intravisit::FnKind; use rustc_hir::{ - Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, FnRetTy, HirId, Impl, - ImplItem, ImplItemKind, IsAuto, Item, ItemKind, LoopSource, MatchSource, MutTy, Node, QPath, TraitItem, + Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, FnRetTy, Safety, HirId, + Impl, ImplItem, ImplItemKind, IsAuto, Item, ItemKind, LoopSource, MatchSource, MutTy, Node, QPath, TraitItem, TraitItemKind, Ty, TyKind, UnOp, UnsafeSource, Unsafety, Variant, VariantData, YieldSource, }; use rustc_lint::{LateContext, LintContext}; @@ -323,7 +323,7 @@ fn ty_search_pat(ty: &Ty<'_>) -> (Pat, Pat) { TyKind::Ptr(MutTy { ty, .. }) => (Pat::Str("*"), ty_search_pat(ty).1), TyKind::Ref(_, MutTy { ty, .. }) => (Pat::Str("&"), ty_search_pat(ty).1), TyKind::BareFn(bare_fn) => ( - if bare_fn.unsafety == Unsafety::Unsafe { + if bare_fn.safety == Safety::Unsafe { Pat::Str("unsafe") } else if bare_fn.abi != Abi::Rust { Pat::Str("extern") diff --git a/src/tools/clippy/clippy_utils/src/hir_utils.rs b/src/tools/clippy/clippy_utils/src/hir_utils.rs index 07c443acb05f7..42dc10ea63066 100644 --- a/src/tools/clippy/clippy_utils/src/hir_utils.rs +++ b/src/tools/clippy/clippy_utils/src/hir_utils.rs @@ -1082,7 +1082,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> { mut_ty.mutbl.hash(&mut self.s); }, TyKind::BareFn(bfn) => { - bfn.unsafety.hash(&mut self.s); + bfn.safety.hash(&mut self.s); bfn.abi.hash(&mut self.s); for arg in bfn.decl.inputs { self.hash_ty(arg); diff --git a/src/tools/clippy/clippy_utils/src/ty.rs b/src/tools/clippy/clippy_utils/src/ty.rs index a06a82c565300..12604bc90ff13 100644 --- a/src/tools/clippy/clippy_utils/src/ty.rs +++ b/src/tools/clippy/clippy_utils/src/ty.rs @@ -9,7 +9,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet}; use rustc_hir as hir; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::def_id::DefId; -use rustc_hir::{Expr, FnDecl, LangItem, TyKind, Unsafety}; +use rustc_hir::{Expr, FnDecl, Safety, LangItem, TyKind}; use rustc_infer::infer::type_variable::TypeVariableOrigin; use rustc_infer::infer::TyCtxtInferExt; use rustc_lint::LateContext; @@ -566,7 +566,7 @@ pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) { /// Returns `true` if the given type is an `unsafe` function. pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { match ty.kind() { - ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).unsafety() == Unsafety::Unsafe, + ty::FnDef(..) | ty::FnPtr(_) => ty.fn_sig(cx.tcx).safety() == Safety::Unsafe, _ => false, } } diff --git a/src/tools/clippy/clippy_utils/src/visitors.rs b/src/tools/clippy/clippy_utils/src/visitors.rs index a3f3b32ed372b..1f131c031ae1a 100644 --- a/src/tools/clippy/clippy_utils/src/visitors.rs +++ b/src/tools/clippy/clippy_utils/src/visitors.rs @@ -5,8 +5,8 @@ use rustc_hir as hir; use rustc_hir::def::{CtorKind, DefKind, Res}; use rustc_hir::intravisit::{self, walk_block, walk_expr, Visitor}; use rustc_hir::{ - AnonConst, Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, HirId, ItemId, ItemKind, LetExpr, Pat, QPath, - Stmt, UnOp, UnsafeSource, Unsafety, + AnonConst, Arm, Block, BlockCheckMode, Body, BodyId, Expr, ExprKind, Safety, HirId, ItemId, ItemKind, LetExpr, + Pat, QPath, Stmt, UnOp, UnsafeSource, Unsafety, }; use rustc_lint::LateContext; use rustc_middle::hir::nested_filter; @@ -421,16 +421,16 @@ pub fn is_expr_unsafe<'tcx>(cx: &LateContext<'tcx>, e: &'tcx Expr<'_>) -> bool { .typeck_results() .type_dependent_def_id(e.hir_id) .map_or(false, |id| { - self.cx.tcx.fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe + self.cx.tcx.fn_sig(id).skip_binder().safety() == Safety::Unsafe }) => { self.is_unsafe = true; }, ExprKind::Call(func, _) => match *self.cx.typeck_results().expr_ty(func).peel_refs().kind() { - ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).skip_binder().unsafety() == Unsafety::Unsafe => { + ty::FnDef(id, _) if self.cx.tcx.fn_sig(id).skip_binder().safety() == Safety::Unsafe => { self.is_unsafe = true; }, - ty::FnPtr(sig) if sig.unsafety() == Unsafety::Unsafe => self.is_unsafe = true, + ty::FnPtr(sig) if sig.safety() == Safety::Unsafe => self.is_unsafe = true, _ => walk_expr(self, e), }, ExprKind::Path(ref p) diff --git a/src/tools/rustfmt/src/items.rs b/src/tools/rustfmt/src/items.rs index f6f51fbd8eaf9..20a29552e07ab 100644 --- a/src/tools/rustfmt/src/items.rs +++ b/src/tools/rustfmt/src/items.rs @@ -290,7 +290,7 @@ pub(crate) struct FnSig<'a> { coroutine_kind: Cow<'a, Option>, constness: ast::Const, defaultness: ast::Defaultness, - unsafety: ast::Unsafe, + safety: ast::Safety, visibility: &'a ast::Visibility, } @@ -301,7 +301,7 @@ impl<'a> FnSig<'a> { visibility: &'a ast::Visibility, ) -> FnSig<'a> { FnSig { - unsafety: method_sig.header.unsafety, + safety: method_sig.header.safety, coroutine_kind: Cow::Borrowed(&method_sig.header.coroutine_kind), constness: method_sig.header.constness, defaultness: ast::Defaultness::Final, @@ -330,7 +330,7 @@ impl<'a> FnSig<'a> { constness: fn_sig.header.constness, coroutine_kind: Cow::Borrowed(&fn_sig.header.coroutine_kind), defaultness, - unsafety: fn_sig.header.unsafety, + safety: fn_sig.header.safety, visibility: vis, }, _ => unreachable!(), @@ -345,7 +345,7 @@ impl<'a> FnSig<'a> { result.push_str(format_constness(self.constness)); self.coroutine_kind .map(|coroutine_kind| result.push_str(format_coro(&coroutine_kind))); - result.push_str(format_unsafety(self.unsafety)); + result.push_str(format_safety(self.safety)); result.push_str(&format_extern( self.ext, context.config.force_explicit_abi(), diff --git a/src/tools/rustfmt/src/types.rs b/src/tools/rustfmt/src/types.rs index fe2d28ae1b9df..75dea90d994c3 100644 --- a/src/tools/rustfmt/src/types.rs +++ b/src/tools/rustfmt/src/types.rs @@ -899,7 +899,7 @@ fn rewrite_bare_fn( result.push_str("> "); } - result.push_str(crate::utils::format_unsafety(bare_fn.unsafety)); + result.push_str(crate::utils::format_safety(bare_fn.safety)); result.push_str(&format_extern( bare_fn.ext, diff --git a/src/tools/rustfmt/src/utils.rs b/src/tools/rustfmt/src/utils.rs index b91d9b47cb63b..465690ee4ebd0 100644 --- a/src/tools/rustfmt/src/utils.rs +++ b/src/tools/rustfmt/src/utils.rs @@ -115,6 +115,14 @@ pub(crate) fn format_unsafety(unsafety: ast::Unsafe) -> &'static str { } } +#[inline] +pub(crate) fn format_safety(unsafety: ast::Safety) -> &'static str { + match unsafety { + ast::Safety::Unsafe(..) => "unsafe ", + ast::Safety::Default => "", + } +} + #[inline] pub(crate) fn format_auto(is_auto: ast::IsAuto) -> &'static str { match is_auto { diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff index 02bf95840dafb..a50a9fb81a7ad 100644 --- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff +++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-abort.diff @@ -69,9 +69,9 @@ + nop; StorageLive(_9); - _9 = _7; -- _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Normal))); +- _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Default))); + _9 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _8 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _8 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Default))); StorageDead(_9); StorageLive(_10); StorageLive(_11); @@ -87,9 +87,9 @@ + nop; StorageLive(_13); - _13 = _7; -- _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Normal))); +- _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Default))); + _13 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _12 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _12 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Default))); StorageDead(_13); StorageLive(_14); StorageLive(_15); diff --git a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff index c5dcc8a8ec9d8..94827ccd0902d 100644 --- a/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff +++ b/tests/mir-opt/gvn.fn_pointers.GVN.panic-unwind.diff @@ -69,9 +69,9 @@ + nop; StorageLive(_9); - _9 = _7; -- _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Normal))); +- _8 = move _9 as fn() (PointerCoercion(ClosureFnPointer(Default))); + _9 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _8 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _8 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Default))); StorageDead(_9); StorageLive(_10); StorageLive(_11); @@ -87,9 +87,9 @@ + nop; StorageLive(_13); - _13 = _7; -- _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Normal))); +- _12 = move _13 as fn() (PointerCoercion(ClosureFnPointer(Default))); + _13 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21}; -+ _12 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Normal))); ++ _12 = const ZeroSized: {closure@$DIR/gvn.rs:610:19: 610:21} as fn() (PointerCoercion(ClosureFnPointer(Default))); StorageDead(_13); StorageLive(_14); StorageLive(_15); diff --git a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir index d7372a0508254..d65b965f70d1e 100644 --- a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir +++ b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-abort.mir @@ -105,7 +105,7 @@ fn main() -> () { StorageLive(_14); _14 = {closure@main::{closure#0}}; Retag(_14); - _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Normal))); + _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Default))); StorageDead(_14); StorageLive(_15); StorageLive(_16); diff --git a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir index 6ec62bfcf8ccb..9fe4362dfddc2 100644 --- a/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir +++ b/tests/mir-opt/retag.main.SimplifyCfg-pre-optimizations.after.panic-unwind.mir @@ -105,7 +105,7 @@ fn main() -> () { StorageLive(_14); _14 = {closure@main::{closure#0}}; Retag(_14); - _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Normal))); + _13 = move _14 as for<'a> fn(&'a i32) -> &'a i32 (PointerCoercion(ClosureFnPointer(Default))); StorageDead(_14); StorageLive(_15); StorageLive(_16);