Rename Unsafe to Safety

This commit is contained in:
Santiago Pastorino 2024-05-17 14:17:48 -03:00
parent 2d89cee625
commit 6b46a919e1
No known key found for this signature in database
GPG key ID: 8131A24E0C79EFAF
115 changed files with 460 additions and 494 deletions

View file

@ -2105,7 +2105,7 @@ impl Ty {
#[derive(Clone, Encodable, Decodable, Debug)] #[derive(Clone, Encodable, Decodable, Debug)]
pub struct BareFnTy { pub struct BareFnTy {
pub unsafety: Unsafe, pub safety: Safety,
pub ext: Extern, pub ext: Extern,
pub generic_params: ThinVec<GenericParam>, pub generic_params: ThinVec<GenericParam>,
pub decl: P<FnDecl>, pub decl: P<FnDecl>,
@ -2484,11 +2484,15 @@ pub enum IsAuto {
No, No,
} }
/// Safety of items.
#[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)] #[derive(Copy, Clone, PartialEq, Eq, Hash, Encodable, Decodable, Debug)]
#[derive(HashStable_Generic)] #[derive(HashStable_Generic)]
pub enum Unsafe { pub enum Safety {
Yes(Span), /// `unsafe` an item is explicitly marked as `unsafe`.
No, 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. /// Describes what kind of coroutine markers, if any, a function has.
@ -2692,7 +2696,7 @@ pub struct ModSpans {
pub struct ForeignMod { pub struct ForeignMod {
/// `unsafe` keyword accepted syntactically for macro DSLs, but not /// `unsafe` keyword accepted syntactically for macro DSLs, but not
/// semantically by Rust. /// semantically by Rust.
pub unsafety: Unsafe, pub safety: Safety,
pub abi: Option<StrLit>, pub abi: Option<StrLit>,
pub items: ThinVec<P<ForeignItem>>, pub items: ThinVec<P<ForeignItem>>,
} }
@ -3011,8 +3015,8 @@ impl Extern {
/// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`). /// included in this struct (e.g., `async unsafe fn` or `const extern "C" fn`).
#[derive(Clone, Copy, Encodable, Decodable, Debug)] #[derive(Clone, Copy, Encodable, Decodable, Debug)]
pub struct FnHeader { pub struct FnHeader {
/// The `unsafe` keyword, if any /// Whether this is `unsafe`, or has a default safety
pub unsafety: Unsafe, pub safety: Safety,
/// Whether this is `async`, `gen`, or nothing. /// Whether this is `async`, `gen`, or nothing.
pub coroutine_kind: Option<CoroutineKind>, pub coroutine_kind: Option<CoroutineKind>,
/// The `const` keyword, if any /// The `const` keyword, if any
@ -3024,8 +3028,8 @@ pub struct FnHeader {
impl FnHeader { impl FnHeader {
/// Does this function header have any qualifiers or is it empty? /// Does this function header have any qualifiers or is it empty?
pub fn has_qualifiers(&self) -> bool { pub fn has_qualifiers(&self) -> bool {
let Self { unsafety, coroutine_kind, constness, ext } = self; let Self { safety, coroutine_kind, constness, ext } = self;
matches!(unsafety, Unsafe::Yes(_)) matches!(safety, Safety::Unsafe(_))
|| coroutine_kind.is_some() || coroutine_kind.is_some()
|| matches!(constness, Const::Yes(_)) || matches!(constness, Const::Yes(_))
|| !matches!(ext, Extern::None) || !matches!(ext, Extern::None)
@ -3035,7 +3039,7 @@ impl FnHeader {
impl Default for FnHeader { impl Default for FnHeader {
fn default() -> FnHeader { fn default() -> FnHeader {
FnHeader { FnHeader {
unsafety: Unsafe::No, safety: Safety::Default,
coroutine_kind: None, coroutine_kind: None,
constness: Const::No, constness: Const::No,
ext: Extern::None, ext: Extern::None,
@ -3045,7 +3049,7 @@ impl Default for FnHeader {
#[derive(Clone, Encodable, Decodable, Debug)] #[derive(Clone, Encodable, Decodable, Debug)]
pub struct Trait { pub struct Trait {
pub unsafety: Unsafe, pub safety: Safety,
pub is_auto: IsAuto, pub is_auto: IsAuto,
pub generics: Generics, pub generics: Generics,
pub bounds: GenericBounds, pub bounds: GenericBounds,
@ -3101,7 +3105,7 @@ pub struct TyAlias {
#[derive(Clone, Encodable, Decodable, Debug)] #[derive(Clone, Encodable, Decodable, Debug)]
pub struct Impl { pub struct Impl {
pub defaultness: Defaultness, pub defaultness: Defaultness,
pub unsafety: Unsafe, pub safety: Safety,
pub generics: Generics, pub generics: Generics,
pub constness: Const, pub constness: Const,
pub polarity: ImplPolarity, pub polarity: ImplPolarity,
@ -3209,7 +3213,7 @@ pub enum ItemKind {
/// E.g., `mod foo;` or `mod foo { .. }`. /// E.g., `mod foo;` or `mod foo { .. }`.
/// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not /// `unsafe` keyword on modules is accepted syntactically for macro DSLs, but not
/// semantically by Rust. /// semantically by Rust.
Mod(Unsafe, ModKind), Mod(Safety, ModKind),
/// An external module (`extern`). /// An external module (`extern`).
/// ///
/// E.g., `extern {}` or `extern "C" {}`. /// E.g., `extern {}` or `extern "C" {}`.

View file

@ -499,8 +499,8 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) {
vis.visit_mt(mt); vis.visit_mt(mt);
} }
TyKind::BareFn(bft) => { TyKind::BareFn(bft) => {
let BareFnTy { unsafety, ext: _, generic_params, decl, decl_span } = bft.deref_mut(); let BareFnTy { safety, ext: _, generic_params, decl, decl_span } = bft.deref_mut();
visit_unsafety(unsafety, vis); visit_safety(safety, vis);
generic_params.flat_map_in_place(|param| vis.flat_map_generic_param(param)); generic_params.flat_map_in_place(|param| vis.flat_map_generic_param(param));
vis.visit_fn_decl(decl); vis.visit_fn_decl(decl);
vis.visit_span(decl_span); vis.visit_span(decl_span);
@ -543,8 +543,8 @@ pub fn noop_visit_ty<T: MutVisitor>(ty: &mut P<Ty>, vis: &mut T) {
} }
fn noop_visit_foreign_mod<T: MutVisitor>(foreign_mod: &mut ForeignMod, vis: &mut T) { fn noop_visit_foreign_mod<T: MutVisitor>(foreign_mod: &mut ForeignMod, vis: &mut T) {
let ForeignMod { unsafety, abi: _, items } = foreign_mod; let ForeignMod { safety, abi: _, items } = foreign_mod;
visit_unsafety(unsafety, vis); visit_safety(safety, vis);
items.flat_map_in_place(|item| vis.flat_map_foreign_item(item)); items.flat_map_in_place(|item| vis.flat_map_foreign_item(item));
} }
@ -859,10 +859,10 @@ fn visit_defaultness<T: MutVisitor>(defaultness: &mut Defaultness, vis: &mut T)
} }
// No `noop_` prefix because there isn't a corresponding method in `MutVisitor`. // No `noop_` prefix because there isn't a corresponding method in `MutVisitor`.
fn visit_unsafety<T: MutVisitor>(unsafety: &mut Unsafe, vis: &mut T) { fn visit_safety<T: MutVisitor>(safety: &mut Safety, vis: &mut T) {
match unsafety { match safety {
Unsafe::Yes(span) => vis.visit_span(span), Safety::Unsafe(span) => vis.visit_span(span),
Unsafe::No => {} Safety::Default => {}
} }
} }
@ -1092,8 +1092,8 @@ impl NoopVisitItemKind for ItemKind {
vis.visit_generics(generics); vis.visit_generics(generics);
visit_opt(body, |body| vis.visit_block(body)); visit_opt(body, |body| vis.visit_block(body));
} }
ItemKind::Mod(unsafety, mod_kind) => { ItemKind::Mod(safety, mod_kind) => {
visit_unsafety(unsafety, vis); visit_safety(safety, vis);
match mod_kind { match mod_kind {
ModKind::Loaded(items, _inline, ModSpans { inner_span, inject_use_span }) => { ModKind::Loaded(items, _inline, ModSpans { inner_span, inject_use_span }) => {
vis.visit_span(inner_span); vis.visit_span(inner_span);
@ -1130,7 +1130,7 @@ impl NoopVisitItemKind for ItemKind {
} }
ItemKind::Impl(box Impl { ItemKind::Impl(box Impl {
defaultness, defaultness,
unsafety, safety,
generics, generics,
constness, constness,
polarity, polarity,
@ -1139,7 +1139,7 @@ impl NoopVisitItemKind for ItemKind {
items, items,
}) => { }) => {
visit_defaultness(defaultness, vis); visit_defaultness(defaultness, vis);
visit_unsafety(unsafety, vis); visit_safety(safety, vis);
vis.visit_generics(generics); vis.visit_generics(generics);
visit_constness(constness, vis); visit_constness(constness, vis);
visit_polarity(polarity, vis); visit_polarity(polarity, vis);
@ -1147,8 +1147,8 @@ impl NoopVisitItemKind for ItemKind {
vis.visit_ty(self_ty); vis.visit_ty(self_ty);
items.flat_map_in_place(|item| vis.flat_map_impl_item(item)); items.flat_map_in_place(|item| vis.flat_map_impl_item(item));
} }
ItemKind::Trait(box Trait { unsafety, is_auto: _, generics, bounds, items }) => { ItemKind::Trait(box Trait { safety, is_auto: _, generics, bounds, items }) => {
visit_unsafety(unsafety, vis); visit_safety(safety, vis);
vis.visit_generics(generics); vis.visit_generics(generics);
visit_bounds(bounds, vis); visit_bounds(bounds, vis);
items.flat_map_in_place(|item| vis.flat_map_trait_item(item)); items.flat_map_in_place(|item| vis.flat_map_trait_item(item));
@ -1254,10 +1254,10 @@ fn visit_const_item<T: MutVisitor>(
} }
fn noop_visit_fn_header<T: MutVisitor>(header: &mut FnHeader, vis: &mut T) { fn noop_visit_fn_header<T: MutVisitor>(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); visit_constness(constness, vis);
coroutine_kind.as_mut().map(|coroutine_kind| vis.visit_coroutine_kind(coroutine_kind)); 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<T: MutVisitor>(krate: &mut Crate, vis: &mut T) { pub fn noop_visit_crate<T: MutVisitor>(krate: &mut Crate, vis: &mut T) {

View file

@ -366,7 +366,7 @@ impl WalkItemKind for ItemKind {
} }
ItemKind::Impl(box Impl { ItemKind::Impl(box Impl {
defaultness: _, defaultness: _,
unsafety: _, safety: _,
generics, generics,
constness: _, constness: _,
polarity: _, polarity: _,
@ -384,7 +384,7 @@ impl WalkItemKind for ItemKind {
try_visit!(visitor.visit_generics(generics)); try_visit!(visitor.visit_generics(generics));
try_visit!(visitor.visit_variant_data(struct_definition)); try_visit!(visitor.visit_variant_data(struct_definition));
} }
ItemKind::Trait(box Trait { unsafety: _, is_auto: _, generics, bounds, items }) => { ItemKind::Trait(box Trait { safety: _, is_auto: _, generics, bounds, items }) => {
try_visit!(visitor.visit_generics(generics)); try_visit!(visitor.visit_generics(generics));
walk_list!(visitor, visit_param_bound, bounds, BoundKind::SuperTraits); walk_list!(visitor, visit_param_bound, bounds, BoundKind::SuperTraits);
walk_list!(visitor, visit_assoc_item, items, AssocCtxt::Trait); walk_list!(visitor, visit_assoc_item, items, AssocCtxt::Trait);

View file

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

View file

@ -323,7 +323,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
hir::ItemKind::Union(vdata, generics) hir::ItemKind::Union(vdata, generics)
} }
ItemKind::Impl(box Impl { ItemKind::Impl(box Impl {
unsafety, safety,
polarity, polarity,
defaultness, defaultness,
constness, constness,
@ -388,7 +388,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)), ImplPolarity::Negative(s) => ImplPolarity::Negative(self.lower_span(*s)),
}; };
hir::ItemKind::Impl(self.arena.alloc(hir::Impl { hir::ItemKind::Impl(self.arena.alloc(hir::Impl {
unsafety: self.lower_unsafety(*unsafety), safety: self.lower_safety(*safety),
polarity, polarity,
defaultness, defaultness,
defaultness_span, defaultness_span,
@ -398,14 +398,14 @@ impl<'hir> LoweringContext<'_, 'hir> {
items: new_impl_items, items: new_impl_items,
})) }))
} }
ItemKind::Trait(box Trait { is_auto, unsafety, generics, bounds, items }) => { ItemKind::Trait(box Trait { is_auto, safety, generics, bounds, items }) => {
// FIXME(const_trait_impl, effects, fee1-dead) this should be simplified if possible // FIXME(const_trait_impl, effects, fee1-dead) this should be simplified if possible
let constness = attrs let constness = attrs
.unwrap_or(&[]) .unwrap_or(&[])
.iter() .iter()
.find(|x| x.has_name(sym::const_trait)) .find(|x| x.has_name(sym::const_trait))
.map_or(Const::No, |x| Const::Yes(x.span)); .map_or(Const::No, |x| Const::Yes(x.span));
let (generics, (unsafety, items, bounds)) = self.lower_generics( let (generics, (safety, items, bounds)) = self.lower_generics(
generics, generics,
constness, constness,
id, id,
@ -418,11 +418,11 @@ impl<'hir> LoweringContext<'_, 'hir> {
let items = this.arena.alloc_from_iter( let items = this.arena.alloc_from_iter(
items.iter().map(|item| this.lower_trait_item_ref(item)), items.iter().map(|item| this.lower_trait_item_ref(item)),
); );
let unsafety = this.lower_unsafety(*unsafety); let safety = this.lower_safety(*safety);
(unsafety, items, bounds) (safety, items, bounds)
}, },
); );
hir::ItemKind::Trait(*is_auto, unsafety, generics, bounds, items) hir::ItemKind::Trait(*is_auto, safety, generics, bounds, items)
} }
ItemKind::TraitAlias(generics, bounds) => { ItemKind::TraitAlias(generics, bounds) => {
let (generics, bounds) = self.lower_generics( let (generics, bounds) = self.lower_generics(
@ -1360,7 +1360,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
hir::IsAsync::NotAsync hir::IsAsync::NotAsync
}; };
hir::FnHeader { hir::FnHeader {
unsafety: self.lower_unsafety(h.unsafety), safety: self.lower_safety(h.safety),
asyncness: asyncness, asyncness: asyncness,
constness: self.lower_constness(h.constness), constness: self.lower_constness(h.constness),
abi: self.lower_extern(h.ext), abi: self.lower_extern(h.ext),
@ -1410,10 +1410,10 @@ impl<'hir> LoweringContext<'_, 'hir> {
} }
} }
pub(super) fn lower_unsafety(&mut self, u: Unsafe) -> hir::Unsafety { pub(super) fn lower_safety(&mut self, s: Safety) -> hir::Safety {
match u { match s {
Unsafe::Yes(_) => hir::Unsafety::Unsafe, Safety::Unsafe(_) => hir::Safety::Unsafe,
Unsafe::No => hir::Unsafety::Normal, Safety::Default => hir::Safety::Safe,
} }
} }

View file

@ -1324,7 +1324,7 @@ impl<'a, 'hir> LoweringContext<'a, 'hir> {
let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params); let generic_params = self.lower_lifetime_binder(t.id, &f.generic_params);
hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy { hir::TyKind::BareFn(self.arena.alloc(hir::BareFnTy {
generic_params, generic_params,
unsafety: self.lower_unsafety(f.unsafety), safety: self.lower_safety(f.safety),
abi: self.lower_extern(f.ext), abi: self.lower_extern(f.ext),
decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None), decl: self.lower_fn_decl(&f.decl, t.id, t.span, FnDeclKind::Pointer, None),
param_names: self.lower_fn_params_to_names(&f.decl), param_names: self.lower_fn_params_to_names(&f.decl),

View file

@ -521,7 +521,7 @@ impl<'a> AstValidator<'a> {
fn check_foreign_fn_headerless( fn check_foreign_fn_headerless(
&self, &self,
// Deconstruct to ensure exhaustiveness // Deconstruct to ensure exhaustiveness
FnHeader { unsafety, coroutine_kind, constness, ext }: FnHeader, FnHeader { safety, coroutine_kind, constness, ext }: FnHeader,
) { ) {
let report_err = |span| { let report_err = |span| {
self.dcx().emit_err(errors::FnQualifierInExtern { self.dcx().emit_err(errors::FnQualifierInExtern {
@ -529,9 +529,9 @@ impl<'a> AstValidator<'a> {
block: self.current_extern_span(), block: self.current_extern_span(),
}); });
}; };
match unsafety { match safety {
Unsafe::Yes(span) => report_err(span), Safety::Unsafe(span) => report_err(span),
Unsafe::No => (), Safety::Default => (),
} }
match coroutine_kind { match coroutine_kind {
Some(knd) => report_err(knd.span()), Some(knd) => report_err(knd.span()),
@ -592,7 +592,7 @@ impl<'a> AstValidator<'a> {
(Some(FnCtxt::Free), Some(header)) => match header.ext { (Some(FnCtxt::Free), Some(header)) => match header.ext {
Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _) Extern::Explicit(StrLit { symbol_unescaped: sym::C, .. }, _)
| Extern::Implicit(_) | Extern::Implicit(_)
if matches!(header.unsafety, Unsafe::Yes(_)) => if matches!(header.safety, Safety::Unsafe(_)) =>
{ {
return; return;
} }
@ -891,7 +891,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
match &item.kind { match &item.kind {
ItemKind::Impl(box Impl { ItemKind::Impl(box Impl {
unsafety, safety,
polarity, polarity,
defaultness: _, defaultness: _,
constness, constness,
@ -910,7 +910,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
// which isn't allowed. Not a problem for this obscure, obsolete syntax. // which isn't allowed. Not a problem for this obscure, obsolete syntax.
this.dcx().emit_fatal(errors::ObsoleteAuto { span: item.span }); this.dcx().emit_fatal(errors::ObsoleteAuto { span: item.span });
} }
if let (&Unsafe::Yes(span), &ImplPolarity::Negative(sp)) = (unsafety, polarity) if let (&Safety::Unsafe(span), &ImplPolarity::Negative(sp)) = (safety, polarity)
{ {
this.dcx().emit_err(errors::UnsafeNegativeImpl { this.dcx().emit_err(errors::UnsafeNegativeImpl {
span: sp.to(t.path.span), span: sp.to(t.path.span),
@ -933,7 +933,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
return; // Avoid visiting again. return; // Avoid visiting again.
} }
ItemKind::Impl(box Impl { ItemKind::Impl(box Impl {
unsafety, safety,
polarity, polarity,
defaultness, defaultness,
constness, constness,
@ -956,7 +956,7 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
&item.vis, &item.vis,
errors::VisibilityNotPermittedNote::IndividualImplItems, errors::VisibilityNotPermittedNote::IndividualImplItems,
); );
if let &Unsafe::Yes(span) = unsafety { if let &Safety::Unsafe(span) = safety {
this.dcx().emit_err(errors::InherentImplCannotUnsafe { this.dcx().emit_err(errors::InherentImplCannotUnsafe {
span: self_ty.span, span: self_ty.span,
annotation_span: span, annotation_span: span,
@ -1020,13 +1020,13 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
walk_list!(self, visit_attribute, &item.attrs); walk_list!(self, visit_attribute, &item.attrs);
return; // Avoid visiting again. return; // Avoid visiting again.
} }
ItemKind::ForeignMod(ForeignMod { abi, unsafety, .. }) => { ItemKind::ForeignMod(ForeignMod { abi, safety, .. }) => {
let old_item = mem::replace(&mut self.extern_mod, Some(item)); let old_item = mem::replace(&mut self.extern_mod, Some(item));
self.visibility_not_permitted( self.visibility_not_permitted(
&item.vis, &item.vis,
errors::VisibilityNotPermittedNote::IndividualForeignItems, errors::VisibilityNotPermittedNote::IndividualForeignItems,
); );
if let &Unsafe::Yes(span) = unsafety { if let &Safety::Unsafe(span) = safety {
self.dcx().emit_err(errors::UnsafeItem { span, kind: "extern block" }); self.dcx().emit_err(errors::UnsafeItem { span, kind: "extern block" });
} }
if abi.is_none() { if abi.is_none() {
@ -1078,8 +1078,8 @@ impl<'a> Visitor<'a> for AstValidator<'a> {
walk_list!(self, visit_attribute, &item.attrs); walk_list!(self, visit_attribute, &item.attrs);
return; // Avoid visiting again return; // Avoid visiting again
} }
ItemKind::Mod(unsafety, mod_kind) => { ItemKind::Mod(safety, mod_kind) => {
if let &Unsafe::Yes(span) = unsafety { if let &Safety::Unsafe(span) = safety {
self.dcx().emit_err(errors::UnsafeItem { span, kind: "module" }); self.dcx().emit_err(errors::UnsafeItem { span, kind: "module" });
} }
// Ensure that `path` attributes on modules are recorded as used (cf. issue #35584). // Ensure that `path` attributes on modules are recorded as used (cf. issue #35584).

View file

@ -524,7 +524,10 @@ pub trait PrintState<'a>: std::ops::Deref<Target = pp::Printer> + std::ops::Dere
} }
} }
fn peek_comment<'b>(&'b self) -> Option<&'b Comment> where 'a: 'b { fn peek_comment<'b>(&'b self) -> Option<&'b Comment>
where
'a: 'b,
{
self.comments().and_then(|c| c.peek()) self.comments().and_then(|c| c.peek())
} }
@ -1150,7 +1153,7 @@ impl<'a> State<'a> {
self.pclose(); self.pclose();
} }
ast::TyKind::BareFn(f) => { 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) => { ast::TyKind::Path(None, path) => {
self.print_path(path, false, 0); self.print_path(path, false, 0);
@ -1908,7 +1911,7 @@ impl<'a> State<'a> {
fn print_ty_fn( fn print_ty_fn(
&mut self, &mut self,
ext: ast::Extern, ext: ast::Extern,
unsafety: ast::Unsafe, safety: ast::Safety,
decl: &ast::FnDecl, decl: &ast::FnDecl,
name: Option<Ident>, name: Option<Ident>,
generic_params: &[ast::GenericParam], generic_params: &[ast::GenericParam],
@ -1924,7 +1927,7 @@ impl<'a> State<'a> {
}, },
span: DUMMY_SP, 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.print_fn(decl, header, name, &generics);
self.end(); self.end();
} }
@ -1932,7 +1935,7 @@ impl<'a> State<'a> {
fn print_fn_header_info(&mut self, header: ast::FnHeader) { fn print_fn_header_info(&mut self, header: ast::FnHeader) {
self.print_constness(header.constness); self.print_constness(header.constness);
header.coroutine_kind.map(|coroutine_kind| self.print_coroutine_kind(coroutine_kind)); 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 { match header.ext {
ast::Extern::None => {} ast::Extern::None => {}
@ -1949,10 +1952,10 @@ impl<'a> State<'a> {
self.word("fn") self.word("fn")
} }
fn print_unsafety(&mut self, s: ast::Unsafe) { fn print_safety(&mut self, s: ast::Safety) {
match s { match s {
ast::Unsafe::No => {} ast::Safety::Default => {}
ast::Unsafe::Yes(_) => self.word_nbsp("unsafe"), ast::Safety::Unsafe(_) => self.word_nbsp("unsafe"),
} }
} }

View file

@ -198,10 +198,10 @@ impl<'a> State<'a> {
&item.attrs, &item.attrs,
); );
} }
ast::ItemKind::Mod(unsafety, mod_kind) => { ast::ItemKind::Mod(safety, mod_kind) => {
self.head(Self::to_string(|s| { self.head(Self::to_string(|s| {
s.print_visibility(&item.vis); s.print_visibility(&item.vis);
s.print_unsafety(*unsafety); s.print_safety(*safety);
s.word("mod"); s.word("mod");
})); }));
self.print_ident(item.ident); self.print_ident(item.ident);
@ -226,7 +226,7 @@ impl<'a> State<'a> {
} }
ast::ItemKind::ForeignMod(nmod) => { ast::ItemKind::ForeignMod(nmod) => {
self.head(Self::to_string(|s| { self.head(Self::to_string(|s| {
s.print_unsafety(nmod.unsafety); s.print_safety(nmod.safety);
s.word("extern"); s.word("extern");
})); }));
if let Some(abi) = nmod.abi { if let Some(abi) = nmod.abi {
@ -275,7 +275,7 @@ impl<'a> State<'a> {
self.print_struct(struct_def, generics, item.ident, item.span, true); self.print_struct(struct_def, generics, item.ident, item.span, true);
} }
ast::ItemKind::Impl(box ast::Impl { ast::ItemKind::Impl(box ast::Impl {
unsafety, safety,
polarity, polarity,
defaultness, defaultness,
constness, constness,
@ -287,7 +287,7 @@ impl<'a> State<'a> {
self.head(""); self.head("");
self.print_visibility(&item.vis); self.print_visibility(&item.vis);
self.print_defaultness(*defaultness); self.print_defaultness(*defaultness);
self.print_unsafety(*unsafety); self.print_safety(*safety);
self.word("impl"); self.word("impl");
if generics.params.is_empty() { if generics.params.is_empty() {
@ -323,7 +323,7 @@ impl<'a> State<'a> {
} }
ast::ItemKind::Trait(box ast::Trait { ast::ItemKind::Trait(box ast::Trait {
is_auto, is_auto,
unsafety, safety,
generics, generics,
bounds, bounds,
items, items,
@ -331,7 +331,7 @@ impl<'a> State<'a> {
}) => { }) => {
self.head(""); self.head("");
self.print_visibility(&item.vis); self.print_visibility(&item.vis);
self.print_unsafety(*unsafety); self.print_safety(*safety);
self.print_is_auto(*is_auto); self.print_is_auto(*is_auto);
self.word_nbsp("trait"); self.word_nbsp("trait");
self.print_ident(item.ident); self.print_ident(item.ident);

View file

@ -1098,7 +1098,7 @@ impl<'a, 'tcx> MirBorrowckCtxt<'a, 'tcx> {
liberated_sig.inputs().iter().copied(), liberated_sig.inputs().iter().copied(),
peeled_ty, peeled_ty,
liberated_sig.c_variadic, liberated_sig.c_variadic,
hir::Unsafety::Normal, hir::Safety::Safe,
rustc_target::spec::abi::Abi::Rust, rustc_target::spec::abi::Abi::Rust,
)), )),
); );

View file

@ -98,7 +98,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
user_provided_sig.inputs().iter().copied(), user_provided_sig.inputs().iter().copied(),
output_ty, output_ty,
user_provided_sig.c_variadic, user_provided_sig.c_variadic,
user_provided_sig.unsafety, user_provided_sig.safety,
user_provided_sig.abi, user_provided_sig.abi,
); );
} }

View file

@ -2007,13 +2007,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() { let sig = match op.ty(body, tcx).kind() {
ty::Closure(_, args) => args.as_closure().sig(), ty::Closure(_, args) => args.as_closure().sig(),
_ => bug!(), _ => bug!(),
}; };
let ty_fn_ptr_from = 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( if let Err(terr) = self.eq_types(
*ty, *ty,

View file

@ -3,7 +3,7 @@ use crate::util::check_builtin_macro_attribute;
use rustc_ast::ptr::P; use rustc_ast::ptr::P;
use rustc_ast::{self as ast, FnHeader, FnSig, Generics, StmtKind}; 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_expand::base::{Annotatable, ExtCtxt};
use rustc_span::symbol::{kw, sym, Ident}; use rustc_span::symbol::{kw, sym, Ident};
use rustc_span::Span; 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 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 params = thin_vec![cx.param(span, size, ty_usize.clone()), cx.param(span, align, ty_usize)];
let decl = cx.fn_decl(params, never); 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 sig = FnSig { decl, header, span: span };
let body = Some(cx.block_expr(call)); let body = Some(cx.block_expr(call));

View file

@ -788,7 +788,7 @@ impl<'a> TraitDef<'a> {
Ident::empty(), Ident::empty(),
attrs, attrs,
ast::ItemKind::Impl(Box::new(ast::Impl { ast::ItemKind::Impl(Box::new(ast::Impl {
unsafety: ast::Unsafe::No, safety: ast::Safety::Default,
polarity: ast::ImplPolarity::Positive, polarity: ast::ImplPolarity::Positive,
defaultness: ast::Defaultness::Final, defaultness: ast::Defaultness::Final,
constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No }, constness: if self.is_const { ast::Const::Yes(DUMMY_SP) } else { ast::Const::No },

View file

@ -6,7 +6,7 @@ use rustc_ast::expand::allocator::{
}; };
use rustc_ast::ptr::P; use rustc_ast::ptr::P;
use rustc_ast::{self as ast, AttrVec, Expr, FnHeader, FnSig, Generics, Param, StmtKind}; 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_expand::base::{Annotatable, ExtCtxt};
use rustc_span::symbol::{kw, sym, Ident, Symbol}; use rustc_span::symbol::{kw, sym, Ident, Symbol};
use rustc_span::Span; use rustc_span::Span;
@ -73,7 +73,7 @@ impl AllocFnFactory<'_, '_> {
let result = self.call_allocator(method.name, args); let result = self.call_allocator(method.name, args);
let output_ty = self.ret_ty(&method.output); let output_ty = self.ret_ty(&method.output);
let decl = self.cx.fn_decl(abi_args, ast::FnRetTy::Ty(output_ty)); 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 sig = FnSig { decl, header, span: self.span };
let body = Some(self.cx.block_expr(result)); let body = Some(self.cx.block_expr(result));
let kind = ItemKind::Fn(Box::new(Fn { let kind = ItemKind::Fn(Box::new(Fn {

View file

@ -549,7 +549,7 @@ fn check_test_signature(
let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic); let has_should_panic_attr = attr::contains_name(&i.attrs, sym::should_panic);
let dcx = cx.dcx(); 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" })); return Err(dcx.emit_err(errors::TestBadFn { span: i.span, cause: span, kind: "unsafe" }));
} }

View file

@ -872,7 +872,7 @@ pub(crate) fn assert_assignable<'tcx>(
let FnSig { let FnSig {
inputs_and_output: types_from, inputs_and_output: types_from,
c_variadic: c_variadic_from, c_variadic: c_variadic_from,
unsafety: unsafety_from, safety: unsafety_from,
abi: abi_from, abi: abi_from,
} = from_sig; } = from_sig;
let to_sig = fx let to_sig = fx
@ -881,7 +881,7 @@ pub(crate) fn assert_assignable<'tcx>(
let FnSig { let FnSig {
inputs_and_output: types_to, inputs_and_output: types_to,
c_variadic: c_variadic_to, c_variadic: c_variadic_to,
unsafety: unsafety_to, safety: unsafety_to,
abi: abi_to, abi: abi_to,
} = to_sig; } = to_sig;
let mut types_from = types_from.iter(); let mut types_from = types_from.iter();

View file

@ -670,11 +670,7 @@ impl<'a, 'gcc, 'tcx> Builder<'a, 'gcc, 'tcx> {
let step3 = self.or(left, right); let step3 = self.or(left, right);
// Fourth step. // Fourth step.
if width == 8 { if width == 8 { step3 } else { self.gcc_bswap(step3, width) }
step3
} else {
self.gcc_bswap(step3, width)
}
} }
128 => { 128 => {
// TODO(antoyo): find a more efficient implementation? // TODO(antoyo): find a more efficient implementation?
@ -1225,7 +1221,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
iter::once(i8p), iter::once(i8p),
tcx.types.unit, tcx.types.unit,
false, false,
rustc_hir::Unsafety::Unsafe, rustc_hir::Safety::Unsafe,
Abi::Rust, Abi::Rust,
)), )),
); );
@ -1236,7 +1232,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
[i8p, i8p].iter().cloned(), [i8p, i8p].iter().cloned(),
tcx.types.unit, tcx.types.unit,
false, false,
rustc_hir::Unsafety::Unsafe, rustc_hir::Safety::Unsafe,
Abi::Rust, Abi::Rust,
)), )),
); );
@ -1245,7 +1241,7 @@ fn get_rust_try_fn<'a, 'gcc, 'tcx>(
[try_fn_ty, i8p, catch_fn_ty], [try_fn_ty, i8p, catch_fn_ty],
tcx.types.i32, tcx.types.i32,
false, false,
rustc_hir::Unsafety::Unsafe, rustc_hir::Safety::Unsafe,
Abi::Rust, Abi::Rust,
)); ));
let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen); let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);

View file

@ -990,7 +990,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[i8p], [i8p],
tcx.types.unit, tcx.types.unit,
false, false,
hir::Unsafety::Unsafe, hir::Safety::Unsafe,
Abi::Rust, Abi::Rust,
)), )),
); );
@ -1001,7 +1001,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[i8p, i8p], [i8p, i8p],
tcx.types.unit, tcx.types.unit,
false, false,
hir::Unsafety::Unsafe, hir::Safety::Unsafe,
Abi::Rust, Abi::Rust,
)), )),
); );
@ -1010,7 +1010,7 @@ fn get_rust_try_fn<'ll, 'tcx>(
[try_fn_ty, i8p, catch_fn_ty], [try_fn_ty, i8p, catch_fn_ty],
tcx.types.i32, tcx.types.i32,
false, false,
hir::Unsafety::Unsafe, hir::Safety::Unsafe,
Abi::Rust, Abi::Rust,
)); ));
let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen); let rust_try = gen_fn(cx, "__rust_try", rust_fn_sig, codegen);

View file

@ -276,7 +276,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
sym::target_feature => { sym::target_feature => {
if !tcx.is_closure_like(did.to_def_id()) if !tcx.is_closure_like(did.to_def_id())
&& let Some(fn_sig) = fn_sig() && let Some(fn_sig) = fn_sig()
&& fn_sig.skip_binder().unsafety() == hir::Unsafety::Normal && fn_sig.skip_binder().safety() == hir::Safety::Safe
{ {
if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc { if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
// The `#[target_feature]` attribute is allowed on // The `#[target_feature]` attribute is allowed on

View file

@ -365,7 +365,7 @@ fn push_debuginfo_type_name<'tcx>(
} }
output.push_str(" (*)("); output.push_str(" (*)(");
} else { } else {
output.push_str(sig.unsafety.prefix_str()); output.push_str(sig.safety.prefix_str());
if sig.abi != rustc_target::spec::abi::Abi::Rust { if sig.abi != rustc_target::spec::abi::Abi::Rust {
output.push_str("extern \""); output.push_str("extern \"");

View file

@ -81,8 +81,8 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
if cfg!(debug_assertions) && stab.promotable { if cfg!(debug_assertions) && stab.promotable {
let sig = tcx.fn_sig(def_id); let sig = tcx.fn_sig(def_id);
assert_eq!( assert_eq!(
sig.skip_binder().unsafety(), sig.skip_binder().safety(),
hir::Unsafety::Normal, hir::Safety::Safe,
"don't mark const unsafe fns as promotable", "don't mark const unsafe fns as promotable",
// https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682 // https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682
); );

View file

@ -2604,7 +2604,7 @@ impl PrimTy {
#[derive(Debug, Clone, Copy, HashStable_Generic)] #[derive(Debug, Clone, Copy, HashStable_Generic)]
pub struct BareFnTy<'hir> { pub struct BareFnTy<'hir> {
pub unsafety: Unsafety, pub safety: Safety,
pub abi: Abi, pub abi: Abi,
pub generic_params: &'hir [GenericParam<'hir>], pub generic_params: &'hir [GenericParam<'hir>],
pub decl: &'hir FnDecl<'hir>, pub decl: &'hir FnDecl<'hir>,
@ -3172,9 +3172,9 @@ impl<'hir> Item<'hir> {
ItemKind::Union(data, gen), (data, gen); ItemKind::Union(data, gen), (data, gen);
expect_trait, expect_trait,
(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]), (IsAuto, Safety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
ItemKind::Trait(is_auto, unsafety, gen, bounds, items), ItemKind::Trait(is_auto, safety, gen, bounds, items),
(*is_auto, *unsafety, gen, bounds, items); (*is_auto, *safety, gen, bounds, items);
expect_trait_alias, (&'hir Generics<'hir>, GenericBounds<'hir>), expect_trait_alias, (&'hir Generics<'hir>, GenericBounds<'hir>),
ItemKind::TraitAlias(gen, bounds), (gen, bounds); ItemKind::TraitAlias(gen, bounds), (gen, bounds);
@ -3185,25 +3185,25 @@ impl<'hir> Item<'hir> {
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)] #[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[derive(Encodable, Decodable, HashStable_Generic)] #[derive(Encodable, Decodable, HashStable_Generic)]
pub enum Unsafety { pub enum Safety {
Unsafe, Unsafe,
Normal, Safe,
} }
impl Unsafety { impl Safety {
pub fn prefix_str(self) -> &'static str { pub fn prefix_str(self) -> &'static str {
match self { match self {
Self::Unsafe => "unsafe ", Self::Unsafe => "unsafe ",
Self::Normal => "", Self::Safe => "",
} }
} }
} }
impl fmt::Display for Unsafety { impl fmt::Display for Safety {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(match *self { f.write_str(match *self {
Self::Unsafe => "unsafe", Self::Unsafe => "unsafe",
Self::Normal => "normal", Self::Safe => "safe",
}) })
} }
} }
@ -3225,7 +3225,7 @@ impl fmt::Display for Constness {
#[derive(Copy, Clone, Debug, HashStable_Generic)] #[derive(Copy, Clone, Debug, HashStable_Generic)]
pub struct FnHeader { pub struct FnHeader {
pub unsafety: Unsafety, pub safety: Safety,
pub constness: Constness, pub constness: Constness,
pub asyncness: IsAsync, pub asyncness: IsAsync,
pub abi: Abi, pub abi: Abi,
@ -3241,7 +3241,7 @@ impl FnHeader {
} }
pub fn is_unsafe(&self) -> bool { pub fn is_unsafe(&self) -> bool {
matches!(&self.unsafety, Unsafety::Unsafe) matches!(&self.safety, Safety::Unsafe)
} }
} }
@ -3284,7 +3284,7 @@ pub enum ItemKind<'hir> {
/// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`. /// A union definition, e.g., `union Foo<A, B> {x: A, y: B}`.
Union(VariantData<'hir>, &'hir Generics<'hir>), Union(VariantData<'hir>, &'hir Generics<'hir>),
/// A trait definition. /// A trait definition.
Trait(IsAuto, Unsafety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]), Trait(IsAuto, Safety, &'hir Generics<'hir>, GenericBounds<'hir>, &'hir [TraitItemRef]),
/// A trait alias. /// A trait alias.
TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>), TraitAlias(&'hir Generics<'hir>, GenericBounds<'hir>),
@ -3294,7 +3294,7 @@ pub enum ItemKind<'hir> {
#[derive(Debug, Clone, Copy, HashStable_Generic)] #[derive(Debug, Clone, Copy, HashStable_Generic)]
pub struct Impl<'hir> { pub struct Impl<'hir> {
pub unsafety: Unsafety, pub safety: Safety,
pub polarity: ImplPolarity, pub polarity: ImplPolarity,
pub defaultness: Defaultness, pub defaultness: Defaultness,
// We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata // We do not put a `Span` in `Defaultness` because it breaks foreign crate metadata

View file

@ -545,7 +545,7 @@ pub fn walk_item<'v, V: Visitor<'v>>(visitor: &mut V, item: &'v Item<'v>) -> V::
try_visit!(visitor.visit_enum_def(enum_definition, item.hir_id())); try_visit!(visitor.visit_enum_def(enum_definition, item.hir_id()));
} }
ItemKind::Impl(Impl { ItemKind::Impl(Impl {
unsafety: _, safety: _,
defaultness: _, defaultness: _,
polarity: _, polarity: _,
defaultness_span: _, defaultness_span: _,

View file

@ -156,7 +156,7 @@ fn check_main_fn_ty(tcx: TyCtxt<'_>, main_def_id: DefId) {
[], [],
expected_return_type, expected_return_type,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::Rust, Abi::Rust,
)); ));
@ -252,7 +252,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, Ty::new_imm_ptr(tcx, Ty::new_imm_ptr(tcx, tcx.types.u8))],
tcx.types.isize, tcx.types.isize,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::Rust, Abi::Rust,
)); ));

View file

@ -71,13 +71,13 @@ fn equate_intrinsic_type<'tcx>(
} }
/// Returns the unsafety of the given intrinsic. /// 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) { 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 { } else {
match tcx.has_attr(intrinsic_id, sym::rustc_safe_intrinsic) { match tcx.has_attr(intrinsic_id, sym::rustc_safe_intrinsic) {
true => hir::Unsafety::Normal, true => hir::Safety::Safe,
false => hir::Unsafety::Unsafe, false => hir::Safety::Unsafe,
} }
}; };
let is_in_list = match tcx.item_name(intrinsic_id.into()) { let is_in_list = match tcx.item_name(intrinsic_id.into()) {
@ -136,8 +136,8 @@ pub fn intrinsic_operation_unsafety(tcx: TyCtxt<'_>, intrinsic_id: LocalDefId) -
| sym::fmul_algebraic | sym::fmul_algebraic
| sym::fdiv_algebraic | sym::fdiv_algebraic
| sym::frem_algebraic | sym::frem_algebraic
| sym::const_eval_select => hir::Unsafety::Normal, | sym::const_eval_select => hir::Safety::Safe,
_ => hir::Unsafety::Unsafe, _ => hir::Safety::Unsafe,
}; };
if has_safe_attr != is_in_list { if has_safe_attr != is_in_list {
@ -197,7 +197,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(); let split: Vec<&str> = name_str.split('_').collect();
assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format"); assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format");
@ -219,9 +219,9 @@ pub fn check_intrinsic_type(
return; return;
} }
}; };
(n_tps, 0, 0, inputs, output, hir::Unsafety::Unsafe) (n_tps, 0, 0, inputs, output, hir::Safety::Unsafe)
} else { } 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 { let (n_tps, n_cts, inputs, output) = match intrinsic_name {
sym::abort => (0, 0, vec![], tcx.types.never), sym::abort => (0, 0, vec![], tcx.types.never),
sym::unreachable => (0, 0, vec![], tcx.types.never), sym::unreachable => (0, 0, vec![], tcx.types.never),
@ -514,14 +514,14 @@ pub fn check_intrinsic_type(
[mut_u8], [mut_u8],
tcx.types.unit, tcx.types.unit,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::Rust, Abi::Rust,
)); ));
let catch_fn_ty = ty::Binder::dummy(tcx.mk_fn_sig( let catch_fn_ty = ty::Binder::dummy(tcx.mk_fn_sig(
[mut_u8, mut_u8], [mut_u8, mut_u8],
tcx.types.unit, tcx.types.unit,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::Rust, Abi::Rust,
)); ));
( (
@ -656,9 +656,9 @@ pub fn check_intrinsic_type(
return; 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); let sig = ty::Binder::bind_with_vars(sig, bound_vars);
equate_intrinsic_type(tcx, span, intrinsic_id, n_tps, n_lts, n_cts, sig) equate_intrinsic_type(tcx, span, intrinsic_id, n_tps, n_lts, n_cts, sig)
} }

View file

@ -456,7 +456,7 @@ fn fn_sig_suggestion<'tcx>(
let output = if !output.is_unit() { format!(" -> {output}") } else { String::new() }; 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); let (generics, where_clauses) = bounds_from_generic_predicates(tcx, predicates);
// FIXME: this is not entirely correct, as the lifetimes from borrowed params will // FIXME: this is not entirely correct, as the lifetimes from borrowed params will
@ -464,9 +464,7 @@ fn fn_sig_suggestion<'tcx>(
// lifetimes between the `impl` and the `trait`, but this should be good enough to // 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 // fill in a significant portion of the missing code, and other subsequent
// suggestions can help the user fix the code. // suggestions can help the user fix the code.
format!( format!("{safety}{asyncness}fn {ident}{generics}({args}){output}{where_clauses} {{ todo!() }}")
"{unsafety}{asyncness}fn {ident}{generics}({args}){output}{where_clauses} {{ todo!() }}"
)
} }
/// Return placeholder code for the given associated item. /// Return placeholder code for the given associated item.

View file

@ -2,7 +2,7 @@
//! crate or pertains to a type defined in this crate. //! crate or pertains to a type defined in this crate.
use rustc_errors::{codes::*, struct_span_code_err}; use rustc_errors::{codes::*, struct_span_code_err};
use rustc_hir::Unsafety; use rustc_hir::Safety;
use rustc_middle::ty::print::PrintTraitRefExt as _; use rustc_middle::ty::print::PrintTraitRefExt as _;
use rustc_middle::ty::{ImplPolarity::*, ImplTraitHeader, TraitDef, TyCtxt}; use rustc_middle::ty::{ImplPolarity::*, ImplTraitHeader, TraitDef, TyCtxt};
use rustc_span::def_id::LocalDefId; use rustc_span::def_id::LocalDefId;
@ -18,8 +18,8 @@ pub(super) fn check_item(
tcx.generics_of(def_id).own_params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle"); tcx.generics_of(def_id).own_params.iter().find(|p| p.pure_wrt_drop).map(|_| "may_dangle");
let trait_ref = trait_header.trait_ref.instantiate_identity(); let trait_ref = trait_header.trait_ref.instantiate_identity();
match (trait_def.unsafety, unsafe_attr, trait_header.unsafety, trait_header.polarity) { match (trait_def.safety, unsafe_attr, trait_header.safety, trait_header.polarity) {
(Unsafety::Normal, None, Unsafety::Unsafe, Positive | Reservation) => { (Safety::Safe, None, Safety::Unsafe, Positive | Reservation) => {
let span = tcx.def_span(def_id); let span = tcx.def_span(def_id);
return Err(struct_span_code_err!( return Err(struct_span_code_err!(
tcx.dcx(), tcx.dcx(),
@ -37,7 +37,7 @@ pub(super) fn check_item(
.emit()); .emit());
} }
(Unsafety::Unsafe, _, Unsafety::Normal, Positive | Reservation) => { (Safety::Unsafe, _, Safety::Safe, Positive | Reservation) => {
let span = tcx.def_span(def_id); let span = tcx.def_span(def_id);
return Err(struct_span_code_err!( return Err(struct_span_code_err!(
tcx.dcx(), tcx.dcx(),
@ -61,7 +61,7 @@ pub(super) fn check_item(
.emit()); .emit());
} }
(Unsafety::Normal, Some(attr_name), Unsafety::Normal, Positive | Reservation) => { (Safety::Safe, Some(attr_name), Safety::Safe, Positive | Reservation) => {
let span = tcx.def_span(def_id); let span = tcx.def_span(def_id);
return Err(struct_span_code_err!( return Err(struct_span_code_err!(
tcx.dcx(), tcx.dcx(),
@ -85,14 +85,14 @@ pub(super) fn check_item(
.emit()); .emit());
} }
(_, _, Unsafety::Unsafe, Negative) => { (_, _, Safety::Unsafe, Negative) => {
// Reported in AST validation // Reported in AST validation
assert!(tcx.dcx().has_errors().is_some(), "unsafe negative impl"); assert!(tcx.dcx().has_errors().is_some(), "unsafe negative impl");
Ok(()) Ok(())
} }
(_, _, Unsafety::Normal, Negative) (_, _, Safety::Safe, Negative)
| (Unsafety::Unsafe, _, Unsafety::Unsafe, Positive | Reservation) | (Safety::Unsafe, _, Safety::Unsafe, Positive | Reservation)
| (Unsafety::Normal, Some(_), Unsafety::Unsafe, Positive | Reservation) | (Safety::Safe, Some(_), Safety::Unsafe, Positive | Reservation)
| (Unsafety::Normal, None, Unsafety::Normal, _) => Ok(()), | (Safety::Safe, None, Safety::Safe, _) => Ok(()),
} }
} }

View file

@ -1102,11 +1102,11 @@ fn adt_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AdtDef<'_> {
fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef { fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
let item = tcx.hir().expect_item(def_id); let item = tcx.hir().expect_item(def_id);
let (is_auto, unsafety, items) = match item.kind { let (is_auto, safety, items) = match item.kind {
hir::ItemKind::Trait(is_auto, unsafety, .., items) => { hir::ItemKind::Trait(is_auto, safety, .., items) => {
(is_auto == hir::IsAuto::Yes, unsafety, items) (is_auto == hir::IsAuto::Yes, safety, items)
} }
hir::ItemKind::TraitAlias(..) => (false, hir::Unsafety::Normal, &[][..]), hir::ItemKind::TraitAlias(..) => (false, hir::Safety::Safe, &[][..]),
_ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"), _ => span_bug!(item.span, "trait_def_of_item invoked on non-trait"),
}; };
@ -1247,7 +1247,7 @@ fn trait_def(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::TraitDef {
ty::TraitDef { ty::TraitDef {
def_id: def_id.to_def_id(), def_id: def_id.to_def_id(),
unsafety, safety,
paren_sugar, paren_sugar,
has_auto_impl: is_auto, has_auto_impl: is_auto,
is_marker, is_marker,
@ -1286,7 +1286,7 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<ty::PolyFnSig<
{ {
icx.lowerer().lower_fn_ty( icx.lowerer().lower_fn_ty(
hir_id, hir_id,
sig.header.unsafety, sig.header.safety,
sig.header.abi, sig.header.abi,
sig.decl, sig.decl,
Some(generics), Some(generics),
@ -1301,14 +1301,9 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<ty::PolyFnSig<
kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _), kind: TraitItemKind::Fn(FnSig { header, decl, span: _ }, _),
generics, generics,
.. ..
}) => icx.lowerer().lower_fn_ty( }) => {
hir_id, icx.lowerer().lower_fn_ty(hir_id, header.safety, header.abi, decl, Some(generics), None)
header.unsafety, }
header.abi,
decl,
Some(generics),
None,
),
ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => { ForeignItem(&hir::ForeignItem { kind: ForeignItemKind::Fn(fn_decl, _, _), .. }) => {
let abi = tcx.hir().get_foreign_abi(hir_id); let abi = tcx.hir().get_foreign_abi(hir_id);
@ -1321,8 +1316,8 @@ fn fn_sig(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::EarlyBinder<ty::PolyFnSig<
let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id).instantiate_identity()); let inputs = data.fields().iter().map(|f| tcx.type_of(f.def_id).instantiate_identity());
// constructors for structs with `layout_scalar_valid_range` are unsafe to call // constructors for structs with `layout_scalar_valid_range` are unsafe to call
let safety = match tcx.layout_scalar_valid_range(adt_def_id) { let safety = match tcx.layout_scalar_valid_range(adt_def_id) {
(Bound::Unbounded, Bound::Unbounded) => hir::Unsafety::Normal, (Bound::Unbounded, Bound::Unbounded) => hir::Safety::Safe,
_ => hir::Unsafety::Unsafe, _ => hir::Safety::Unsafe,
}; };
ty::Binder::dummy(tcx.mk_fn_sig(inputs, ty, false, safety, abi::Abi::Rust)) ty::Binder::dummy(tcx.mk_fn_sig(inputs, ty, false, safety, abi::Abi::Rust))
} }
@ -1409,13 +1404,13 @@ fn infer_return_ty_for_fn_sig<'tcx>(
fn_sig.inputs().iter().copied(), fn_sig.inputs().iter().copied(),
recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)), recovered_ret_ty.unwrap_or_else(|| Ty::new_error(tcx, guar)),
fn_sig.c_variadic, fn_sig.c_variadic,
fn_sig.unsafety, fn_sig.safety,
fn_sig.abi, fn_sig.abi,
)) ))
} }
None => icx.lowerer().lower_fn_ty( None => icx.lowerer().lower_fn_ty(
hir_id, hir_id,
sig.header.unsafety, sig.header.safety,
sig.header.abi, sig.header.abi,
sig.decl, sig.decl,
Some(generics), Some(generics),
@ -1574,7 +1569,7 @@ fn impl_trait_header(tcx: TyCtxt<'_>, def_id: LocalDefId) -> Option<ty::ImplTrai
}; };
ty::ImplTraitHeader { ty::ImplTraitHeader {
trait_ref: ty::EarlyBinder::bind(trait_ref), trait_ref: ty::EarlyBinder::bind(trait_ref),
unsafety: impl_.unsafety, safety: impl_.safety,
polarity: polarity_of_impl(tcx, def_id, impl_, item.span) polarity: polarity_of_impl(tcx, def_id, impl_, item.span)
} }
}) })
@ -1685,14 +1680,14 @@ fn compute_sig_of_foreign_fn_decl<'tcx>(
decl: &'tcx hir::FnDecl<'tcx>, decl: &'tcx hir::FnDecl<'tcx>,
abi: abi::Abi, abi: abi::Abi,
) -> ty::PolyFnSig<'tcx> { ) -> ty::PolyFnSig<'tcx> {
let unsafety = if abi == abi::Abi::RustIntrinsic { let safety = if abi == abi::Abi::RustIntrinsic {
intrinsic_operation_unsafety(tcx, def_id) intrinsic_operation_unsafety(tcx, def_id)
} else { } else {
hir::Unsafety::Unsafe hir::Safety::Unsafe
}; };
let hir_id = tcx.local_def_id_to_hir_id(def_id); let hir_id = tcx.local_def_id_to_hir_id(def_id);
let fty = 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 // Feature gate SIMD types in FFI, since I am not sure that the
// ABIs are handled at all correctly. -huonw // ABIs are handled at all correctly. -huonw

View file

@ -2080,14 +2080,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
Ty::new_fn_ptr( Ty::new_fn_ptr(
tcx, tcx,
self.lower_fn_ty( self.lower_fn_ty(hir_ty.hir_id, bf.safety, bf.abi, bf.decl, None, Some(hir_ty)),
hir_ty.hir_id,
bf.unsafety,
bf.abi,
bf.decl,
None,
Some(hir_ty),
),
) )
} }
hir::TyKind::TraitObject(bounds, lifetime, repr) => { hir::TyKind::TraitObject(bounds, lifetime, repr) => {
@ -2309,11 +2302,11 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
} }
/// Lower a function type from the HIR to our internal notion of a function signature. /// 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( pub fn lower_fn_ty(
&self, &self,
hir_id: HirId, hir_id: HirId,
unsafety: hir::Unsafety, safety: hir::Safety,
abi: abi::Abi, abi: abi::Abi,
decl: &hir::FnDecl<'tcx>, decl: &hir::FnDecl<'tcx>,
generics: Option<&hir::Generics<'_>>, generics: Option<&hir::Generics<'_>>,
@ -2376,7 +2369,7 @@ impl<'tcx> dyn HirTyLowerer<'tcx> + '_ {
debug!(?output_ty); 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); 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()) { if !self.allow_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {

View file

@ -287,7 +287,7 @@ impl<'a> State<'a> {
self.pclose(); self.pclose();
} }
hir::TyKind::BareFn(f) => { 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::OpaqueDef(..) => self.word("/*impl Trait*/"),
hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false), hir::TyKind::Path(ref qpath) => self.print_qpath(qpath, false),
@ -351,7 +351,7 @@ impl<'a> State<'a> {
self.print_fn( self.print_fn(
decl, decl,
hir::FnHeader { hir::FnHeader {
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
constness: hir::Constness::NotConst, constness: hir::Constness::NotConst,
abi: Abi::Rust, abi: Abi::Rust,
asyncness: hir::IsAsync::NotAsync, asyncness: hir::IsAsync::NotAsync,
@ -582,7 +582,7 @@ impl<'a> State<'a> {
self.print_struct(struct_def, generics, item.ident.name, item.span, true); self.print_struct(struct_def, generics, item.ident.name, item.span, true);
} }
hir::ItemKind::Impl(&hir::Impl { hir::ItemKind::Impl(&hir::Impl {
unsafety, safety,
polarity, polarity,
defaultness, defaultness,
defaultness_span: _, defaultness_span: _,
@ -593,7 +593,7 @@ impl<'a> State<'a> {
}) => { }) => {
self.head(""); self.head("");
self.print_defaultness(defaultness); self.print_defaultness(defaultness);
self.print_unsafety(unsafety); self.print_safety(safety);
self.word_nbsp("impl"); self.word_nbsp("impl");
if !generics.params.is_empty() { if !generics.params.is_empty() {
@ -622,10 +622,10 @@ impl<'a> State<'a> {
} }
self.bclose(item.span); self.bclose(item.span);
} }
hir::ItemKind::Trait(is_auto, unsafety, generics, bounds, trait_items) => { hir::ItemKind::Trait(is_auto, safety, generics, bounds, trait_items) => {
self.head(""); self.head("");
self.print_is_auto(is_auto); self.print_is_auto(is_auto);
self.print_unsafety(unsafety); self.print_safety(safety);
self.word_nbsp("trait"); self.word_nbsp("trait");
self.print_ident(item.ident); self.print_ident(item.ident);
self.print_generic_params(generics.params); self.print_generic_params(generics.params);
@ -2234,7 +2234,7 @@ impl<'a> State<'a> {
fn print_ty_fn( fn print_ty_fn(
&mut self, &mut self,
abi: Abi, abi: Abi,
unsafety: hir::Unsafety, safety: hir::Safety,
decl: &hir::FnDecl<'_>, decl: &hir::FnDecl<'_>,
name: Option<Symbol>, name: Option<Symbol>,
generic_params: &[hir::GenericParam<'_>], generic_params: &[hir::GenericParam<'_>],
@ -2246,7 +2246,7 @@ impl<'a> State<'a> {
self.print_fn( self.print_fn(
decl, decl,
hir::FnHeader { hir::FnHeader {
unsafety, safety,
abi, abi,
constness: hir::Constness::NotConst, constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync, asyncness: hir::IsAsync::NotAsync,
@ -2267,7 +2267,7 @@ impl<'a> State<'a> {
hir::IsAsync::Async(_) => self.word_nbsp("async"), hir::IsAsync::Async(_) => self.word_nbsp("async"),
} }
self.print_unsafety(header.unsafety); self.print_safety(header.safety);
if header.abi != Abi::Rust { if header.abi != Abi::Rust {
self.word_nbsp("extern"); self.word_nbsp("extern");
@ -2284,10 +2284,10 @@ impl<'a> State<'a> {
} }
} }
fn print_unsafety(&mut self, s: hir::Unsafety) { fn print_safety(&mut self, s: hir::Safety) {
match s { match s {
hir::Unsafety::Normal => {} hir::Safety::Safe => {}
hir::Unsafety::Unsafe => self.word_nbsp("unsafe"), hir::Safety::Unsafe => self.word_nbsp("unsafe"),
} }
} }

View file

@ -201,7 +201,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
tupled_upvars_ty, tupled_upvars_ty,
), ),
coroutine_closure_sig.c_variadic, coroutine_closure_sig.c_variadic,
coroutine_closure_sig.unsafety, coroutine_closure_sig.safety,
coroutine_closure_sig.abi, coroutine_closure_sig.abi,
); );
let adjustments = self.adjust_steps(autoderef); let adjustments = self.adjust_steps(autoderef);

View file

@ -216,7 +216,7 @@ fn check_panic_info_fn(tcx: TyCtxt<'_>, fn_id: LocalDefId, fn_sig: ty::FnSig<'_>
ty::BoundVariableKind::Region(ty::BrAnon), ty::BoundVariableKind::Region(ty::BrAnon),
]); ]);
let expected_sig = ty::Binder::bind_with_vars( 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, bounds,
); );
@ -239,7 +239,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 generic_ty = Ty::new_param(tcx, fn_generic.index, fn_generic.name);
let main_fn_ty = Ty::new_fn_ptr( let main_fn_ty = Ty::new_fn_ptr(
tcx, 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::Safe, Abi::Rust)),
); );
let expected_sig = ty::Binder::dummy(tcx.mk_fn_sig( let expected_sig = ty::Binder::dummy(tcx.mk_fn_sig(
@ -251,7 +251,7 @@ fn check_lang_start_fn<'tcx>(tcx: TyCtxt<'tcx>, fn_sig: ty::FnSig<'tcx>, def_id:
], ],
tcx.types.isize, tcx.types.isize,
false, false,
fn_sig.unsafety, fn_sig.safety,
Abi::Rust, Abi::Rust,
)); ));

View file

@ -89,7 +89,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
[Ty::new_tup(tcx, sig.inputs())], [Ty::new_tup(tcx, sig.inputs())],
sig.output(), sig.output(),
sig.c_variadic, sig.c_variadic,
sig.unsafety, sig.safety,
sig.abi, sig.abi,
) )
}); });
@ -238,7 +238,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
], ],
Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]), Ty::new_tup(tcx, &[bound_yield_ty, bound_return_ty]),
sig.c_variadic, sig.c_variadic,
sig.unsafety, sig.safety,
sig.abi, sig.abi,
) )
}), }),
@ -281,7 +281,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
liberated_sig.inputs().iter().copied(), liberated_sig.inputs().iter().copied(),
coroutine_output_ty, coroutine_output_ty,
liberated_sig.c_variadic, liberated_sig.c_variadic,
liberated_sig.unsafety, liberated_sig.safety,
liberated_sig.abi, liberated_sig.abi,
); );
@ -493,7 +493,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
input_tys, input_tys,
ret_param_ty, ret_param_ty,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::Rust, Abi::Rust,
)); ));
@ -605,7 +605,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
sig.inputs().iter().cloned(), sig.inputs().iter().cloned(),
sig.output(), sig.output(),
sig.c_variadic, sig.c_variadic,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::RustCall, Abi::RustCall,
) )
}); });
@ -743,7 +743,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
inputs, inputs,
supplied_output_ty, supplied_output_ty,
expected_sigs.liberated_sig.c_variadic, expected_sigs.liberated_sig.c_variadic,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::RustCall, Abi::RustCall,
); );
@ -820,7 +820,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
supplied_arguments, supplied_arguments,
supplied_return, supplied_return,
decl.c_variadic, decl.c_variadic,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::RustCall, Abi::RustCall,
), ),
bound_vars, bound_vars,
@ -984,7 +984,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
supplied_arguments, supplied_arguments,
err_ty, err_ty,
decl.c_variadic, decl.c_variadic,
hir::Unsafety::Normal, hir::Safety::Safe,
Abi::RustCall, Abi::RustCall,
)); ));

View file

@ -788,8 +788,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
let outer_universe = self.infcx.universe(); let outer_universe = self.infcx.universe();
let result = if let ty::FnPtr(fn_ty_b) = b.kind() let result = if let ty::FnPtr(fn_ty_b) = b.kind()
&& let (hir::Unsafety::Normal, hir::Unsafety::Unsafe) = && let (hir::Safety::Safe, hir::Safety::Unsafe) =
(fn_ty_a.unsafety(), fn_ty_b.unsafety()) (fn_ty_a.safety(), fn_ty_b.safety())
{ {
let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a); let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
self.unify_and(unsafe_a, b, to_unsafe) self.unify_and(unsafe_a, b, to_unsafe)
@ -851,7 +851,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396). // 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::Safe
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty() && !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
{ {
return Err(TypeError::TargetFeatureCast(def_id)); return Err(TypeError::TargetFeatureCast(def_id));
@ -922,14 +922,14 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
// or // or
// `unsafe fn(arg0,arg1,...) -> _` // `unsafe fn(arg0,arg1,...) -> _`
let closure_sig = args_a.as_closure().sig(); let closure_sig = args_a.as_closure().sig();
let unsafety = fn_ty.unsafety(); let safety = fn_ty.safety();
let pointer_ty = 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); debug!("coerce_closure_to_fn(a={:?}, b={:?}, pty={:?})", a, b, pointer_ty);
self.unify_and( self.unify_and(
pointer_ty, pointer_ty,
b, b,
simple(Adjust::Pointer(PointerCoercion::ClosureFnPointer(unsafety))), simple(Adjust::Pointer(PointerCoercion::ClosureFnPointer(safety))),
) )
} }
_ => self.unify_and(a, b, identity), _ => self.unify_and(a, b, identity),
@ -1126,27 +1126,25 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
(ty::Closure(_, args), ty::FnDef(..)) => { (ty::Closure(_, args), ty::FnDef(..)) => {
let b_sig = new_ty.fn_sig(self.tcx); let b_sig = new_ty.fn_sig(self.tcx);
let a_sig = 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)) (Some(a_sig), Some(b_sig))
} }
(ty::FnDef(..), ty::Closure(_, args)) => { (ty::FnDef(..), ty::Closure(_, args)) => {
let a_sig = prev_ty.fn_sig(self.tcx); let a_sig = prev_ty.fn_sig(self.tcx);
let b_sig = 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)) (Some(a_sig), Some(b_sig))
} }
(ty::Closure(_, args_a), ty::Closure(_, args_b)) => { (ty::Closure(_, args_a), ty::Closure(_, args_b)) => (
( Some(
Some(self.tcx.signature_unclosure( self.tcx
args_a.as_closure().sig(), .signature_unclosure(args_a.as_closure().sig(), hir::Safety::Safe),
hir::Unsafety::Normal, ),
)), Some(
Some(self.tcx.signature_unclosure( self.tcx
args_b.as_closure().sig(), .signature_unclosure(args_b.as_closure().sig(), hir::Safety::Safe),
hir::Unsafety::Normal, ),
)), ),
)
}
_ => (None, None), _ => (None, None),
} }
} }
@ -1168,14 +1166,14 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
let fn_ptr = Ty::new_fn_ptr(self.tcx, sig); let fn_ptr = Ty::new_fn_ptr(self.tcx, sig);
let prev_adjustment = match prev_ty.kind() { let prev_adjustment = match prev_ty.kind() {
ty::Closure(..) => { ty::Closure(..) => {
Adjust::Pointer(PointerCoercion::ClosureFnPointer(a_sig.unsafety())) Adjust::Pointer(PointerCoercion::ClosureFnPointer(a_sig.safety()))
} }
ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer), ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer),
_ => span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"), _ => span_bug!(cause.span, "should not try to coerce a {prev_ty} to a fn pointer"),
}; };
let next_adjustment = match new_ty.kind() { let next_adjustment = match new_ty.kind() {
ty::Closure(..) => { ty::Closure(..) => {
Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.unsafety())) Adjust::Pointer(PointerCoercion::ClosureFnPointer(b_sig.safety()))
} }
ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer), ty::FnDef(..) => Adjust::Pointer(PointerCoercion::ReifyFnPointer),
_ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"), _ => span_bug!(new.span, "should not try to coerce a {new_ty} to a fn pointer"),

View file

@ -558,7 +558,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
if let Some(def_id) = typeck_results.type_dependent_def_id(ex.hir_id) if let Some(def_id) = typeck_results.type_dependent_def_id(ex.hir_id)
&& let method_ty = self.root_ctxt.tcx.type_of(def_id).instantiate_identity() && let method_ty = self.root_ctxt.tcx.type_of(def_id).instantiate_identity()
&& let sig = method_ty.fn_sig(self.root_ctxt.tcx) && let sig = method_ty.fn_sig(self.root_ctxt.tcx)
&& let hir::Unsafety::Unsafe = sig.unsafety() && let hir::Safety::Unsafe = sig.safety()
{ {
let mut collector = InferVarCollector { let mut collector = InferVarCollector {
value: (ex.hir_id, ex.span, UnsafeUseReason::Method), value: (ex.hir_id, ex.span, UnsafeUseReason::Method),
@ -578,7 +578,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
if func_ty.is_fn() if func_ty.is_fn()
&& let sig = func_ty.fn_sig(self.root_ctxt.tcx) && let sig = func_ty.fn_sig(self.root_ctxt.tcx)
&& let hir::Unsafety::Unsafe = sig.unsafety() && let hir::Safety::Unsafe = sig.safety()
{ {
let mut collector = InferVarCollector { let mut collector = InferVarCollector {
value: (ex.hir_id, ex.span, UnsafeUseReason::Call), value: (ex.hir_id, ex.span, UnsafeUseReason::Call),
@ -609,7 +609,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
// `is_fn` excludes closures, but those can't be unsafe. // `is_fn` excludes closures, but those can't be unsafe.
if ty.is_fn() if ty.is_fn()
&& let sig = ty.fn_sig(self.root_ctxt.tcx) && let sig = ty.fn_sig(self.root_ctxt.tcx)
&& let hir::Unsafety::Unsafe = sig.unsafety() && let hir::Safety::Unsafe = sig.safety()
{ {
let mut collector = InferVarCollector { let mut collector = InferVarCollector {
value: (ex.hir_id, ex.span, UnsafeUseReason::Path), value: (ex.hir_id, ex.span, UnsafeUseReason::Path),

View file

@ -145,7 +145,7 @@ fn typeck_with_fallback<'tcx>(
if let Some(hir::FnSig { header, decl, .. }) = node.fn_sig() { if let Some(hir::FnSig { header, decl, .. }) = node.fn_sig() {
let fn_sig = if decl.output.get_infer_ret_ty().is_some() { 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 { } else {
tcx.fn_sig(def_id).instantiate_identity() tcx.fn_sig(def_id).instantiate_identity()
}; };

View file

@ -419,7 +419,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
[], [],
tupled_upvars_ty_for_borrow, tupled_upvars_ty_for_borrow,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
rustc_target::spec::abi::Abi::Rust, rustc_target::spec::abi::Abi::Rust,
), ),
self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region( self.tcx.mk_bound_variable_kinds(&[ty::BoundVariableKind::Region(

View file

@ -1053,8 +1053,8 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
// unsafe extern "C" for<'a> fn(&'a T) -> &'a T // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
// ^^^^^^ // ^^^^^^
values.0.push(sig1.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety); values.0.push(sig1.safety.prefix_str(), sig1.safety != sig2.safety);
values.1.push(sig2.unsafety.prefix_str(), sig1.unsafety != sig2.unsafety); values.1.push(sig2.safety.prefix_str(), sig1.safety != sig2.safety);
// unsafe extern "C" for<'a> fn(&'a T) -> &'a T // unsafe extern "C" for<'a> fn(&'a T) -> &'a T
// ^^^^^^^^^^ // ^^^^^^^^^^
@ -1928,7 +1928,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
self.tcx self.tcx
.signature_unclosure( .signature_unclosure(
args.as_closure().sig(), args.as_closure().sig(),
rustc_hir::Unsafety::Normal, rustc_hir::Safety::Safe,
) )
.to_string(), .to_string(),
), ),

View file

@ -168,7 +168,7 @@ impl<'tcx> TypeFolder<TyCtxt<'tcx>> for ClosureEraser<'tcx> {
let closure_sig = args.as_closure().sig(); let closure_sig = args.as_closure().sig();
Ty::new_fn_ptr( Ty::new_fn_ptr(
self.tcx, self.tcx,
self.tcx.signature_unclosure(closure_sig, hir::Unsafety::Normal), self.tcx.signature_unclosure(closure_sig, hir::Safety::Safe),
) )
} }
_ => ty.super_fold_with(self), _ => ty.super_fold_with(self),

View file

@ -409,10 +409,8 @@ impl<'tcx> NiceRegionError<'_, 'tcx> {
{ {
let closure_sig = self_ty.map(|closure| { let closure_sig = self_ty.map(|closure| {
if let ty::Closure(_, args) = closure.kind() { if let ty::Closure(_, args) = closure.kind() {
self.tcx().signature_unclosure( self.tcx()
args.as_closure().sig(), .signature_unclosure(args.as_closure().sig(), rustc_hir::Safety::Safe)
rustc_hir::Unsafety::Normal,
)
} else { } else {
bug!("type is not longer closure"); bug!("type is not longer closure");
} }

View file

@ -452,7 +452,7 @@ impl<T> Trait<T> for X {
} }
(ty::FnPtr(sig), ty::FnDef(def_id, _)) (ty::FnPtr(sig), ty::FnDef(def_id, _))
| (ty::FnDef(def_id, _), ty::FnPtr(sig)) => { | (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( diag.note(
"unsafe functions cannot be coerced into safe function pointers", "unsafe functions cannot be coerced into safe function pointers",
); );

View file

@ -360,11 +360,11 @@ impl EarlyLintPass for UnsafeCode {
fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) { fn check_item(&mut self, cx: &EarlyContext<'_>, it: &ast::Item) {
match it.kind { match it.kind {
ast::ItemKind::Trait(box ast::Trait { unsafety: ast::Unsafe::Yes(_), .. }) => { ast::ItemKind::Trait(box ast::Trait { safety: ast::Safety::Unsafe(_), .. }) => {
self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait); self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeTrait);
} }
ast::ItemKind::Impl(box ast::Impl { unsafety: ast::Unsafe::Yes(_), .. }) => { ast::ItemKind::Impl(box ast::Impl { safety: ast::Safety::Unsafe(_), .. }) => {
self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl); self.report_unsafe(cx, it.span, BuiltinUnsafe::UnsafeImpl);
} }
@ -419,7 +419,7 @@ impl EarlyLintPass for UnsafeCode {
if let FnKind::Fn( if let FnKind::Fn(
ctxt, ctxt,
_, _,
ast::FnSig { header: ast::FnHeader { unsafety: ast::Unsafe::Yes(_), .. }, .. }, ast::FnSig { header: ast::FnHeader { safety: ast::Safety::Unsafe(_), .. }, .. },
_, _,
_, _,
body, body,

View file

@ -345,8 +345,8 @@ fn structurally_same_type_impl<'tcx>(
let a_sig = tcx.instantiate_bound_regions_with_erased(a_poly_sig); let a_sig = tcx.instantiate_bound_regions_with_erased(a_poly_sig);
let b_sig = tcx.instantiate_bound_regions_with_erased(b_poly_sig); let b_sig = tcx.instantiate_bound_regions_with_erased(b_poly_sig);
(a_sig.abi, a_sig.unsafety, a_sig.c_variadic) (a_sig.abi, a_sig.safety, a_sig.c_variadic)
== (b_sig.abi, b_sig.unsafety, b_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| { && a_sig.inputs().iter().eq_by(b_sig.inputs().iter(), |a, b| {
structurally_same_type_impl(seen_types, tcx, param_env, *a, *b, ckind) structurally_same_type_impl(seen_types, tcx, param_env, *a, *b, ckind)
}) })

View file

@ -15,7 +15,7 @@ pub enum PointerCoercion {
/// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer. /// Go from a non-capturing closure to an fn pointer or an unsafe fn pointer.
/// It cannot convert a closure that requires unsafe. /// 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. /// Go from a mut raw pointer to a const raw pointer.
MutToConstPointer, MutToConstPointer,

View file

@ -114,7 +114,7 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
type AllocId = crate::mir::interpret::AllocId; type AllocId = crate::mir::interpret::AllocId;
type Pat = Pattern<'tcx>; type Pat = Pattern<'tcx>;
type Unsafety = hir::Unsafety; type Safety = hir::Safety;
type Abi = abi::Abi; type Abi = abi::Abi;
type Const = ty::Const<'tcx>; type Const = ty::Const<'tcx>;
@ -235,7 +235,7 @@ impl<'tcx> rustc_type_ir::inherent::Abi<TyCtxt<'tcx>> for abi::Abi {
} }
} }
impl<'tcx> rustc_type_ir::inherent::Unsafety<TyCtxt<'tcx>> for hir::Unsafety { impl<'tcx> rustc_type_ir::inherent::Safety<TyCtxt<'tcx>> for hir::Safety {
fn prefix_str(self) -> &'static str { fn prefix_str(self) -> &'static str {
self.prefix_str() self.prefix_str()
} }
@ -2024,11 +2024,8 @@ impl<'tcx> TyCtxt<'tcx> {
/// that is, a `fn` type that is equivalent in every way for being /// that is, a `fn` type that is equivalent in every way for being
/// unsafe. /// unsafe.
pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> { pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
assert_eq!(sig.unsafety(), hir::Unsafety::Normal); assert_eq!(sig.safety(), hir::Safety::Safe);
Ty::new_fn_ptr( Ty::new_fn_ptr(self, sig.map_bound(|sig| ty::FnSig { safety: hir::Safety::Unsafe, ..sig }))
self,
sig.map_bound(|sig| ty::FnSig { unsafety: hir::Unsafety::Unsafe, ..sig }),
)
} }
/// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name` /// Given the def_id of a Trait `trait_def_id` and the name of an associated item `assoc_name`
@ -2085,20 +2082,16 @@ impl<'tcx> TyCtxt<'tcx> {
/// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then /// and so forth -- so e.g., if we have a sig with `Fn<(u32, i32)>` then
/// you would get a `fn(u32, i32)`. /// you would get a `fn(u32, i32)`.
/// `unsafety` determines the unsafety of the fn signature. If you pass /// `unsafety` determines the unsafety of the fn signature. If you pass
/// `hir::Unsafety::Unsafe` in the previous example, then you would get /// `hir::Safety::Unsafe` in the previous example, then you would get
/// an `unsafe fn (u32, i32)`. /// an `unsafe fn (u32, i32)`.
/// It cannot convert a closure that requires unsafe. /// It cannot convert a closure that requires unsafe.
pub fn signature_unclosure( pub fn signature_unclosure(self, sig: PolyFnSig<'tcx>, safety: hir::Safety) -> PolyFnSig<'tcx> {
self,
sig: PolyFnSig<'tcx>,
unsafety: hir::Unsafety,
) -> PolyFnSig<'tcx> {
sig.map_bound(|s| { sig.map_bound(|s| {
let params = match s.inputs()[0].kind() { let params = match s.inputs()[0].kind() {
ty::Tuple(params) => *params, ty::Tuple(params) => *params,
_ => bug!(), _ => 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)
}) })
} }
@ -2365,7 +2358,7 @@ impl<'tcx> TyCtxt<'tcx> {
inputs: I, inputs: I,
output: I::Item, output: I::Item,
c_variadic: bool, c_variadic: bool,
unsafety: hir::Unsafety, safety: hir::Safety,
abi: abi::Abi, abi: abi::Abi,
) -> T::Output ) -> T::Output
where where
@ -2375,7 +2368,7 @@ impl<'tcx> TyCtxt<'tcx> {
T::collect_and_apply(inputs.into_iter().chain(iter::once(output)), |xs| ty::FnSig { T::collect_and_apply(inputs.into_iter().chain(iter::once(output)), |xs| ty::FnSig {
inputs_and_output: self.mk_type_list(xs), inputs_and_output: self.mk_type_list(xs),
c_variadic, c_variadic,
unsafety, safety,
abi, abi,
}) })
} }

View file

@ -34,7 +34,7 @@ pub enum TypeError<'tcx> {
Mismatch, Mismatch,
ConstnessMismatch(ExpectedFound<ty::BoundConstness>), ConstnessMismatch(ExpectedFound<ty::BoundConstness>),
PolarityMismatch(ExpectedFound<ty::PredicatePolarity>), PolarityMismatch(ExpectedFound<ty::PredicatePolarity>),
UnsafetyMismatch(ExpectedFound<hir::Unsafety>), SafetyMismatch(ExpectedFound<hir::Safety>),
AbiMismatch(ExpectedFound<abi::Abi>), AbiMismatch(ExpectedFound<abi::Abi>),
Mutability, Mutability,
ArgumentMutability(usize), ArgumentMutability(usize),
@ -107,7 +107,7 @@ impl<'tcx> TypeError<'tcx> {
format!("expected {} polarity, found {} polarity", values.expected, values.found) format!("expected {} polarity, found {} polarity", values.expected, values.found)
.into() .into()
} }
UnsafetyMismatch(values) => { SafetyMismatch(values) => {
format!("expected {} fn, found {} fn", values.expected, values.found).into() format!("expected {} fn, found {} fn", values.expected, values.found).into()
} }
AbiMismatch(values) => { AbiMismatch(values) => {
@ -204,7 +204,7 @@ impl<'tcx> TypeError<'tcx> {
pub fn must_include_note(self) -> bool { pub fn must_include_note(self) -> bool {
use self::TypeError::*; use self::TypeError::*;
match self { match self {
CyclicTy(_) | CyclicConst(_) | UnsafetyMismatch(_) | ConstnessMismatch(_) CyclicTy(_) | CyclicConst(_) | SafetyMismatch(_) | ConstnessMismatch(_)
| PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_) | PolarityMismatch(_) | Mismatch | AbiMismatch(_) | FixedArraySize(_)
| ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_) | ArgumentSorts(..) | Sorts(_) | IntMismatch(_) | FloatMismatch(_)
| VariadicMismatch(_) | TargetFeatureCast(_) => false, | VariadicMismatch(_) | TargetFeatureCast(_) => false,

View file

@ -281,13 +281,13 @@ impl DeepRejectCtxt {
} }
ty::FnPtr(obl_sig) => match k { ty::FnPtr(obl_sig) => match k {
ty::FnPtr(impl_sig) => { 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(); obl_sig.skip_binder();
let impl_sig = impl_sig.skip_binder(); let impl_sig = impl_sig.skip_binder();
abi == impl_sig.abi abi == impl_sig.abi
&& c_variadic == impl_sig.c_variadic && c_variadic == impl_sig.c_variadic
&& unsafety == impl_sig.unsafety && safety == impl_sig.safety
&& inputs_and_output.len() == impl_sig.inputs_and_output.len() && inputs_and_output.len() == impl_sig.inputs_and_output.len()
&& iter::zip(inputs_and_output, impl_sig.inputs_and_output) && iter::zip(inputs_and_output, impl_sig.inputs_and_output)
.all(|(obl, imp)| self.types_may_unify(obl, imp)) .all(|(obl, imp)| self.types_may_unify(obl, imp))

View file

@ -266,7 +266,7 @@ pub struct ImplHeader<'tcx> {
pub struct ImplTraitHeader<'tcx> { pub struct ImplTraitHeader<'tcx> {
pub trait_ref: ty::EarlyBinder<ty::TraitRef<'tcx>>, pub trait_ref: ty::EarlyBinder<ty::TraitRef<'tcx>>,
pub polarity: ImplPolarity, pub polarity: ImplPolarity,
pub unsafety: hir::Unsafety, pub safety: hir::Safety,
} }
#[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)] #[derive(Copy, Clone, PartialEq, Eq, Debug, TypeFoldable, TypeVisitable)]

View file

@ -3035,7 +3035,7 @@ define_print! {
(self, cx): (self, cx):
ty::FnSig<'tcx> { ty::FnSig<'tcx> {
p!(write("{}", self.unsafety.prefix_str())); p!(write("{}", self.safety.prefix_str()));
if self.abi != Abi::Rust { if self.abi != Abi::Rust {
p!(write("extern {} ", self.abi)); p!(write("extern {} ", self.abi));

View file

@ -146,7 +146,7 @@ impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
if a.c_variadic != b.c_variadic { if a.c_variadic != b.c_variadic {
return Err(TypeError::VariadicMismatch(expected_found(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)?; let abi = relation.relate(a.abi, b.abi)?;
if a.inputs().len() != b.inputs().len() { if a.inputs().len() != b.inputs().len() {
@ -181,7 +181,7 @@ impl<'tcx> Relate<'tcx> for ty::FnSig<'tcx> {
Ok(ty::FnSig { Ok(ty::FnSig {
inputs_and_output: tcx.mk_type_list_from_iter(inputs_and_output)?, inputs_and_output: tcx.mk_type_list_from_iter(inputs_and_output)?,
c_variadic: a.c_variadic, c_variadic: a.c_variadic,
unsafety, safety,
abi, abi,
}) })
} }
@ -197,13 +197,13 @@ impl<'tcx> Relate<'tcx> for ty::BoundConstness {
} }
} }
impl<'tcx> Relate<'tcx> for hir::Unsafety { impl<'tcx> Relate<'tcx> for hir::Safety {
fn relate<R: TypeRelation<'tcx>>( fn relate<R: TypeRelation<'tcx>>(
_relation: &mut R, _relation: &mut R,
a: hir::Unsafety, a: hir::Safety,
b: hir::Unsafety, b: hir::Safety,
) -> RelateResult<'tcx, hir::Unsafety> { ) -> RelateResult<'tcx, hir::Safety> {
if a != b { Err(TypeError::UnsafetyMismatch(expected_found(a, b))) } else { Ok(a) } if a != b { Err(TypeError::SafetyMismatch(expected_found(a, b))) } else { Ok(a) }
} }
} }

View file

@ -355,7 +355,7 @@ TrivialTypeTraversalImpls! {
// interners). // interners).
TrivialTypeTraversalAndLiftImpls! { TrivialTypeTraversalAndLiftImpls! {
::rustc_hir::def_id::DefId, ::rustc_hir::def_id::DefId,
::rustc_hir::Unsafety, ::rustc_hir::Safety,
::rustc_target::spec::abi::Abi, ::rustc_target::spec::abi::Abi,
crate::ty::ClosureKind, crate::ty::ClosureKind,
crate::ty::ParamConst, crate::ty::ParamConst,

View file

@ -388,7 +388,7 @@ impl<'tcx> CoroutineClosureArgs<'tcx> {
yield_ty, yield_ty,
return_ty, return_ty,
c_variadic: sig.c_variadic, c_variadic: sig.c_variadic,
unsafety: sig.unsafety, safety: sig.safety,
abi: sig.abi, abi: sig.abi,
} }
}) })
@ -416,8 +416,8 @@ pub struct CoroutineClosureSignature<'tcx> {
// from scratch just for good measure. // from scratch just for good measure.
/// Always false /// Always false
pub c_variadic: bool, pub c_variadic: bool,
/// Always [`hir::Unsafety::Normal`] /// Always [`hir::Safety::Safe`]
pub unsafety: hir::Unsafety, pub safety: hir::Safety,
/// Always [`abi::Abi::RustCall`] /// Always [`abi::Abi::RustCall`]
pub abi: abi::Abi, pub abi: abi::Abi,
} }
@ -1129,8 +1129,8 @@ impl<'tcx> PolyFnSig<'tcx> {
self.skip_binder().c_variadic self.skip_binder().c_variadic
} }
pub fn unsafety(&self) -> hir::Unsafety { pub fn safety(&self) -> hir::Safety {
self.skip_binder().unsafety self.skip_binder().safety
} }
pub fn abi(&self) -> abi::Abi { pub fn abi(&self) -> abi::Abi {
@ -1140,12 +1140,7 @@ impl<'tcx> PolyFnSig<'tcx> {
pub fn is_fn_trait_compatible(&self) -> bool { pub fn is_fn_trait_compatible(&self) -> bool {
matches!( matches!(
self.skip_binder(), self.skip_binder(),
ty::FnSig { ty::FnSig { safety: rustc_hir::Safety::Safe, abi: Abi::Rust, c_variadic: false, .. }
unsafety: rustc_hir::Unsafety::Normal,
abi: Abi::Rust,
c_variadic: false,
..
}
) )
} }
} }
@ -1991,7 +1986,7 @@ impl<'tcx> Ty<'tcx> {
ty::Binder::dummy(ty::FnSig { ty::Binder::dummy(ty::FnSig {
inputs_and_output: ty::List::empty(), inputs_and_output: ty::List::empty(),
c_variadic: false, c_variadic: false,
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
abi: abi::Abi::Rust, abi: abi::Abi::Rust,
}) })
} }

View file

@ -15,7 +15,7 @@ use rustc_macros::{Decodable, Encodable, HashStable};
pub struct TraitDef { pub struct TraitDef {
pub def_id: DefId, pub def_id: DefId,
pub unsafety: hir::Unsafety, pub safety: hir::Safety,
/// If `true`, then this trait had the `#[rustc_paren_sugar]` /// If `true`, then this trait had the `#[rustc_paren_sugar]`
/// attribute, indicating that it should be used with `Foo()` /// attribute, indicating that it should be used with `Foo()`

View file

@ -65,7 +65,7 @@ impl<'tcx> Value<TyCtxt<'tcx>> for ty::Binder<'_, ty::FnSig<'_>> {
std::iter::repeat(err).take(arity), std::iter::repeat(err).take(arity),
err, err,
false, false,
rustc_hir::Unsafety::Normal, rustc_hir::Safety::Safe,
rustc_target::spec::abi::Abi::Rust, rustc_target::spec::abi::Abi::Rust,
)); ));

View file

@ -391,7 +391,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
return; // don't visit the whole expression return; // don't visit the whole expression
} }
ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => { ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
if self.thir[fun].ty.fn_sig(self.tcx).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() { let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
Some(*func_id) Some(*func_id)
} else { } else {
@ -921,7 +921,7 @@ pub fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
let hir_id = tcx.local_def_id_to_hir_id(def); let hir_id = tcx.local_def_id_to_hir_id(def);
let safety_context = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| { let safety_context = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
if fn_sig.header.unsafety == hir::Unsafety::Unsafe { if fn_sig.header.safety == hir::Safety::Unsafe {
SafetyContext::UnsafeFn SafetyContext::UnsafeFn
} else { } else {
SafetyContext::Safe SafetyContext::Safe

View file

@ -158,7 +158,7 @@ impl<'tcx> FunctionItemRefChecker<'_, 'tcx> {
.lint_root; .lint_root;
// FIXME: use existing printing routines to print the function signature // 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 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() { let abi = match fn_sig.abi() {
Abi::Rust => String::from(""), Abi::Rust => String::from(""),
other_abi => { other_abi => {

View file

@ -1047,7 +1047,7 @@ fn build_construct_coroutine_by_move_shim<'tcx>(
args.as_coroutine_closure().coroutine_captures_by_ref_ty(), args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
), ),
sig.c_variadic, sig.c_variadic,
sig.unsafety, sig.safety,
sig.abi, sig.abi,
) )
}); });

View file

@ -33,7 +33,7 @@ impl<'a> Parser<'a> {
/// Parses a `mod <foo> { ... }` or `mod <foo>;` item. /// Parses a `mod <foo> { ... }` or `mod <foo>;` item.
fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> { fn parse_item_mod(&mut self, attrs: &mut AttrVec) -> PResult<'a, ItemInfo> {
let unsafety = self.parse_unsafety(Case::Sensitive); let safety = self.parse_safety(Case::Sensitive);
self.expect_keyword(kw::Mod)?; self.expect_keyword(kw::Mod)?;
let id = self.parse_ident()?; let id = self.parse_ident()?;
let mod_kind = if self.eat(&token::Semi) { let mod_kind = if self.eat(&token::Semi) {
@ -45,7 +45,7 @@ impl<'a> Parser<'a> {
attrs.extend(inner_attrs); attrs.extend(inner_attrs);
ModKind::Loaded(items, Inline::Yes, inner_span) ModKind::Loaded(items, Inline::Yes, inner_span)
}; };
Ok((id, ItemKind::Mod(unsafety, mod_kind))) Ok((id, ItemKind::Mod(safety, mod_kind)))
} }
/// Parses the contents of a module (inner attributes followed by module items). /// Parses the contents of a module (inner attributes followed by module items).
@ -210,13 +210,13 @@ impl<'a> Parser<'a> {
self.parse_item_extern_crate()? self.parse_item_extern_crate()?
} else { } else {
// EXTERN BLOCK // EXTERN BLOCK
self.parse_item_foreign_mod(attrs, Unsafe::No)? self.parse_item_foreign_mod(attrs, Safety::Default)?
} }
} else if self.is_unsafe_foreign_mod() { } else if self.is_unsafe_foreign_mod() {
// EXTERN BLOCK // EXTERN BLOCK
let unsafety = self.parse_unsafety(Case::Sensitive); let safety = self.parse_safety(Case::Sensitive);
self.expect_keyword(kw::Extern)?; self.expect_keyword(kw::Extern)?;
self.parse_item_foreign_mod(attrs, unsafety)? self.parse_item_foreign_mod(attrs, safety)?
} else if self.is_static_global() { } else if self.is_static_global() {
// STATIC ITEM // STATIC ITEM
self.bump(); // `static` self.bump(); // `static`
@ -540,7 +540,7 @@ impl<'a> Parser<'a> {
attrs: &mut AttrVec, attrs: &mut AttrVec,
defaultness: Defaultness, defaultness: Defaultness,
) -> PResult<'a, ItemInfo> { ) -> PResult<'a, ItemInfo> {
let unsafety = self.parse_unsafety(Case::Sensitive); let safety = self.parse_safety(Case::Sensitive);
self.expect_keyword(kw::Impl)?; self.expect_keyword(kw::Impl)?;
// First, parse generic parameters if necessary. // First, parse generic parameters if necessary.
@ -646,7 +646,7 @@ impl<'a> Parser<'a> {
let trait_ref = TraitRef { path, ref_id: ty_first.id }; let trait_ref = TraitRef { path, ref_id: ty_first.id };
ItemKind::Impl(Box::new(Impl { ItemKind::Impl(Box::new(Impl {
unsafety, safety,
polarity, polarity,
defaultness, defaultness,
constness, constness,
@ -659,7 +659,7 @@ impl<'a> Parser<'a> {
None => { None => {
// impl Type // impl Type
ItemKind::Impl(Box::new(Impl { ItemKind::Impl(Box::new(Impl {
unsafety, safety,
polarity, polarity,
defaultness, defaultness,
constness, constness,
@ -864,7 +864,7 @@ impl<'a> Parser<'a> {
/// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`. /// Parses `unsafe? auto? trait Foo { ... }` or `trait Foo = Bar;`.
fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> { fn parse_item_trait(&mut self, attrs: &mut AttrVec, lo: Span) -> PResult<'a, ItemInfo> {
let unsafety = self.parse_unsafety(Case::Sensitive); let safety = self.parse_safety(Case::Sensitive);
// Parse optional `auto` prefix. // Parse optional `auto` prefix.
let is_auto = if self.eat_keyword(kw::Auto) { let is_auto = if self.eat_keyword(kw::Auto) {
self.psess.gated_spans.gate(sym::auto_traits, self.prev_token.span); self.psess.gated_spans.gate(sym::auto_traits, self.prev_token.span);
@ -898,7 +898,7 @@ impl<'a> Parser<'a> {
if is_auto == IsAuto::Yes { if is_auto == IsAuto::Yes {
self.dcx().emit_err(errors::TraitAliasCannotBeAuto { span: whole_span }); self.dcx().emit_err(errors::TraitAliasCannotBeAuto { span: whole_span });
} }
if let Unsafe::Yes(_) = unsafety { if let Safety::Unsafe(_) = safety {
self.dcx().emit_err(errors::TraitAliasCannotBeUnsafe { span: whole_span }); self.dcx().emit_err(errors::TraitAliasCannotBeUnsafe { span: whole_span });
} }
@ -911,7 +911,7 @@ impl<'a> Parser<'a> {
let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?; let items = self.parse_item_list(attrs, |p| p.parse_trait_item(ForceCollect::No))?;
Ok(( Ok((
ident, ident,
ItemKind::Trait(Box::new(Trait { is_auto, unsafety, generics, bounds, items })), ItemKind::Trait(Box::new(Trait { is_auto, safety, generics, bounds, items })),
)) ))
} }
} }
@ -1172,19 +1172,19 @@ impl<'a> Parser<'a> {
fn parse_item_foreign_mod( fn parse_item_foreign_mod(
&mut self, &mut self,
attrs: &mut AttrVec, attrs: &mut AttrVec,
mut unsafety: Unsafe, mut safety: Safety,
) -> PResult<'a, ItemInfo> { ) -> PResult<'a, ItemInfo> {
let abi = self.parse_abi(); // ABI? let abi = self.parse_abi(); // ABI?
if unsafety == Unsafe::No if safety == Safety::Default
&& self.token.is_keyword(kw::Unsafe) && self.token.is_keyword(kw::Unsafe)
&& self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace)) && self.look_ahead(1, |t| t.kind == token::OpenDelim(Delimiter::Brace))
{ {
self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err().emit(); self.expect(&token::OpenDelim(Delimiter::Brace)).unwrap_err().emit();
unsafety = Unsafe::Yes(self.token.span); safety = Safety::Unsafe(self.token.span);
self.eat_keyword(kw::Unsafe); self.eat_keyword(kw::Unsafe);
} }
let module = ast::ForeignMod { let module = ast::ForeignMod {
unsafety, safety,
abi, abi,
items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?, items: self.parse_item_list(attrs, |p| p.parse_foreign_item(ForceCollect::No))?,
}; };
@ -2456,7 +2456,7 @@ impl<'a> Parser<'a> {
let coroutine_kind = self.parse_coroutine_kind(case); let coroutine_kind = self.parse_coroutine_kind(case);
let unsafe_start_sp = self.token.span; 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_start_sp = self.token.span;
let ext = self.parse_extern(case); let ext = self.parse_extern(case);
@ -2494,7 +2494,7 @@ impl<'a> Parser<'a> {
// We may be able to recover // We may be able to recover
let mut recover_constness = constness; let mut recover_constness = constness;
let mut recover_coroutine_kind = coroutine_kind; 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 // 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. // that the keyword is already present and the second instance should be removed.
let wrong_kw = if self.check_keyword(kw::Const) { let wrong_kw = if self.check_keyword(kw::Const) {
@ -2532,10 +2532,10 @@ impl<'a> Parser<'a> {
} }
} }
} else if self.check_keyword(kw::Unsafe) { } else if self.check_keyword(kw::Unsafe) {
match unsafety { match safety {
Unsafe::Yes(sp) => Some(WrongKw::Duplicated(sp)), Safety::Unsafe(sp) => Some(WrongKw::Duplicated(sp)),
Unsafe::No => { Safety::Default => {
recover_unsafety = Unsafe::Yes(self.token.span); recover_safety = Safety::Unsafe(self.token.span);
Some(WrongKw::Misplaced(ext_start_sp)) Some(WrongKw::Misplaced(ext_start_sp))
} }
} }
@ -2620,7 +2620,7 @@ impl<'a> Parser<'a> {
err.emit(); err.emit();
return Ok(FnHeader { return Ok(FnHeader {
constness: recover_constness, constness: recover_constness,
unsafety: recover_unsafety, safety: recover_safety,
coroutine_kind: recover_coroutine_kind, coroutine_kind: recover_coroutine_kind,
ext, ext,
}); });
@ -2631,7 +2631,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. /// Parses the parameter list and result type of a function declaration.

View file

@ -26,7 +26,7 @@ use rustc_ast::tokenstream::{TokenStream, TokenTree, TokenTreeCursor};
use rustc_ast::util::case::Case; use rustc_ast::util::case::Case;
use rustc_ast::{ use rustc_ast::{
self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs, self as ast, AnonConst, AttrArgs, AttrArgsEq, AttrId, ByRef, Const, CoroutineKind, DelimArgs,
Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, StrLit, Unsafe, Visibility, Expr, ExprKind, Extern, HasAttrs, HasTokens, Mutability, Recovered, Safety, StrLit, Visibility,
VisibilityKind, DUMMY_NODE_ID, VisibilityKind, DUMMY_NODE_ID,
}; };
use rustc_ast_pretty::pprust; use rustc_ast_pretty::pprust;
@ -1217,12 +1217,12 @@ impl<'a> Parser<'a> {
} }
} }
/// Parses unsafety: `unsafe` or nothing. /// Parses fn unsafety: `unsafe`, `safe` or nothing.
fn parse_unsafety(&mut self, case: Case) -> Unsafe { fn parse_safety(&mut self, case: Case) -> Safety {
if self.eat_keyword_case(kw::Unsafe, case) { if self.eat_keyword_case(kw::Unsafe, case) {
Unsafe::Yes(self.prev_token.uninterpolated_span()) Safety::Unsafe(self.prev_token.uninterpolated_span())
} else { } else {
Unsafe::No Safety::Default
} }
} }

View file

@ -590,7 +590,7 @@ impl<'a> Parser<'a> {
tokens: None, tokens: None,
}; };
let span_start = self.token.span; 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)?; self.parse_fn_front_matter(&inherited_vis, Case::Sensitive)?;
if self.may_recover() && self.token.kind == TokenKind::Lt { if self.may_recover() && self.token.kind == TokenKind::Lt {
self.recover_fn_ptr_with_generics(lo, &mut params, param_insertion_point)?; 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()` // FIXME(gen_blocks): emit a similar error for `gen fn()`
let decl_span = span_start.to(self.token.span); 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)`). /// Recover from function pointer types with a generic parameter list (e.g. `fn<'a>(&'a str)`).

View file

@ -17,7 +17,7 @@ use rustc_hir::{self as hir};
use rustc_hir::{ use rustc_hir::{
self, FnSig, ForeignItem, HirId, Item, ItemKind, TraitItem, CRATE_HIR_ID, CRATE_OWNER_ID, 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_macros::LintDiagnostic;
use rustc_middle::bug; use rustc_middle::bug;
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
@ -2335,7 +2335,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
}), }),
token_stream, token_stream,
false, false,
Unsafety::Normal, Safety::Safe,
Abi::Rust, Abi::Rust,
); );
@ -2362,7 +2362,7 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
cause.span = ty.span; cause.span = ty.span;
} }
} }
TypeError::UnsafetyMismatch(_) => { TypeError::SafetyMismatch(_) => {
// FIXME: Would be nice if we had a span here.. // FIXME: Would be nice if we had a span here..
} }
TypeError::AbiMismatch(_) => { TypeError::AbiMismatch(_) => {

View file

@ -216,7 +216,7 @@ impl RustcInternal for FnSig {
tcx.lift(rustc_ty::FnSig { tcx.lift(rustc_ty::FnSig {
inputs_and_output: tcx.mk_type_list(&self.inputs_and_output.internal(tables, tcx)), inputs_and_output: tcx.mk_type_list(&self.inputs_and_output.internal(tables, tcx)),
c_variadic: self.c_variadic, c_variadic: self.c_variadic,
unsafety: self.unsafety.internal(tables, tcx), safety: self.safety.internal(tables, tcx),
abi: self.abi.internal(tables, tcx), abi: self.abi.internal(tables, tcx),
}) })
.unwrap() .unwrap()
@ -481,16 +481,15 @@ impl RustcInternal for Abi {
} }
impl RustcInternal for Safety { impl RustcInternal for Safety {
type T<'tcx> = rustc_hir::Unsafety; type T<'tcx> = rustc_hir::Safety;
fn internal<'tcx>(&self, _tables: &mut Tables<'_>, _tcx: TyCtxt<'tcx>) -> Self::T<'tcx> { fn internal<'tcx>(&self, _tables: &mut Tables<'_>, _tcx: TyCtxt<'tcx>) -> Self::T<'tcx> {
match self { match self {
Safety::Unsafe => rustc_hir::Unsafety::Unsafe, Safety::Unsafe => rustc_hir::Safety::Unsafe,
Safety::Normal => rustc_hir::Unsafety::Normal, Safety::Safe => rustc_hir::Safety::Safe,
} }
} }
} }
impl RustcInternal for Span { impl RustcInternal for Span {
type T<'tcx> = rustc_span::Span; type T<'tcx> = rustc_span::Span;

View file

@ -9,12 +9,12 @@ mod error;
mod mir; mod mir;
mod ty; mod ty;
impl<'tcx> Stable<'tcx> for rustc_hir::Unsafety { impl<'tcx> Stable<'tcx> for rustc_hir::Safety {
type T = stable_mir::mir::Safety; type T = stable_mir::mir::Safety;
fn stable(&self, _: &mut Tables<'_>) -> Self::T { fn stable(&self, _: &mut Tables<'_>) -> Self::T {
match self { match self {
rustc_hir::Unsafety::Unsafe => stable_mir::mir::Safety::Unsafe, rustc_hir::Safety::Unsafe => stable_mir::mir::Safety::Unsafe,
rustc_hir::Unsafety::Normal => stable_mir::mir::Safety::Normal, rustc_hir::Safety::Safe => stable_mir::mir::Safety::Safe,
} }
} }
} }

View file

@ -112,8 +112,8 @@ impl<'tcx> Stable<'tcx> for ty::adjustment::PointerCoercion {
match self { match self {
PointerCoercion::ReifyFnPointer => stable_mir::mir::PointerCoercion::ReifyFnPointer, PointerCoercion::ReifyFnPointer => stable_mir::mir::PointerCoercion::ReifyFnPointer,
PointerCoercion::UnsafeFnPointer => stable_mir::mir::PointerCoercion::UnsafeFnPointer, PointerCoercion::UnsafeFnPointer => stable_mir::mir::PointerCoercion::UnsafeFnPointer,
PointerCoercion::ClosureFnPointer(unsafety) => { PointerCoercion::ClosureFnPointer(safety) => {
stable_mir::mir::PointerCoercion::ClosureFnPointer(unsafety.stable(tables)) stable_mir::mir::PointerCoercion::ClosureFnPointer(safety.stable(tables))
} }
PointerCoercion::MutToConstPointer => { PointerCoercion::MutToConstPointer => {
stable_mir::mir::PointerCoercion::MutToConstPointer stable_mir::mir::PointerCoercion::MutToConstPointer
@ -215,7 +215,7 @@ impl<'tcx> Stable<'tcx> for ty::FnSig<'tcx> {
FnSig { FnSig {
inputs_and_output: self.inputs_and_output.iter().map(|ty| ty.stable(tables)).collect(), inputs_and_output: self.inputs_and_output.iter().map(|ty| ty.stable(tables)).collect(),
c_variadic: self.c_variadic, c_variadic: self.c_variadic,
unsafety: self.unsafety.stable(tables), safety: self.safety.stable(tables),
abi: self.abi.stable(tables), abi: self.abi.stable(tables),
} }
} }
@ -499,7 +499,7 @@ impl<'tcx> Stable<'tcx> for ty::TraitDef {
TraitDecl { TraitDecl {
def_id: tables.trait_def(self.def_id), def_id: tables.trait_def(self.def_id),
unsafety: self.unsafety.stable(tables), safety: self.safety.stable(tables),
paren_sugar: self.paren_sugar, paren_sugar: self.paren_sugar,
has_auto_impl: self.has_auto_impl, has_auto_impl: self.has_auto_impl,
is_marker: self.is_marker, is_marker: self.is_marker,

View file

@ -424,7 +424,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
ty::FnPtr(sig) => { ty::FnPtr(sig) => {
self.push("F"); self.push("F");
self.in_binder(&sig, |cx, sig| { self.in_binder(&sig, |cx, sig| {
if sig.unsafety == hir::Unsafety::Unsafe { if sig.safety == hir::Safety::Unsafe {
cx.push("U"); cx.push("U");
} }
match sig.abi { match sig.abi {

View file

@ -205,9 +205,9 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
if self_ty.is_fn() { if self_ty.is_fn() {
let fn_sig = self_ty.fn_sig(self.tcx); let fn_sig = self_ty.fn_sig(self.tcx);
let shortname = match fn_sig.unsafety() { let shortname = match fn_sig.safety() {
hir::Unsafety::Normal => "fn", hir::Safety::Safe => "fn",
hir::Unsafety::Unsafe => "unsafe fn", hir::Safety::Unsafe => "unsafe fn",
}; };
flags.push((sym::_Self, Some(shortname.to_owned()))); flags.push((sym::_Self, Some(shortname.to_owned())));
} }

View file

@ -1897,7 +1897,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
*inputs, *inputs,
infcx.next_ty_var(DUMMY_SP), infcx.next_ty_var(DUMMY_SP),
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
abi::Abi::Rust, abi::Abi::Rust,
) )
} }
@ -1905,7 +1905,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
[inputs], [inputs],
infcx.next_ty_var(DUMMY_SP), infcx.next_ty_var(DUMMY_SP),
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
abi::Abi::Rust, abi::Abi::Rust,
), ),
}; };
@ -3925,7 +3925,7 @@ impl<'tcx> TypeErrCtxt<'_, 'tcx> {
&& let fn_sig @ ty::FnSig { && let fn_sig @ ty::FnSig {
abi: abi::Abi::Rust, abi: abi::Abi::Rust,
c_variadic: false, c_variadic: false,
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
.. ..
} = fn_ty.fn_sig(tcx).skip_binder() } = fn_ty.fn_sig(tcx).skip_binder()

View file

@ -1712,7 +1712,7 @@ fn confirm_closure_candidate<'cx, 'tcx>(
[sig.tupled_inputs_ty], [sig.tupled_inputs_ty],
output_ty, output_ty,
sig.c_variadic, sig.c_variadic,
sig.unsafety, sig.safety,
sig.abi, sig.abi,
) )
}) })

View file

@ -37,7 +37,7 @@ fn fn_sig_for_fn_abi<'tcx>(
[], [],
tcx.thread_local_ptr_ty(instance.def_id()), tcx.thread_local_ptr_ty(instance.def_id()),
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
rustc_target::spec::abi::Abi::Unadjusted, rustc_target::spec::abi::Abi::Unadjusted,
)); ));
} }
@ -96,7 +96,7 @@ fn fn_sig_for_fn_abi<'tcx>(
iter::once(env_ty).chain(sig.inputs().iter().cloned()), iter::once(env_ty).chain(sig.inputs().iter().cloned()),
sig.output(), sig.output(),
sig.c_variadic, sig.c_variadic,
sig.unsafety, sig.safety,
sig.abi, sig.abi,
), ),
bound_vars, bound_vars,
@ -150,7 +150,7 @@ fn fn_sig_for_fn_abi<'tcx>(
args.as_coroutine_closure().coroutine_captures_by_ref_ty(), args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
), ),
sig.c_variadic, sig.c_variadic,
sig.unsafety, sig.safety,
sig.abi, sig.abi,
), ),
bound_vars, bound_vars,
@ -301,7 +301,7 @@ fn fn_sig_for_fn_abi<'tcx>(
[env_ty, resume_ty], [env_ty, resume_ty],
ret_ty, ret_ty,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
rustc_target::spec::abi::Abi::Rust, rustc_target::spec::abi::Abi::Rust,
) )
} else { } else {
@ -310,7 +310,7 @@ fn fn_sig_for_fn_abi<'tcx>(
[env_ty], [env_ty],
ret_ty, ret_ty,
false, false,
hir::Unsafety::Normal, hir::Safety::Safe,
rustc_target::spec::abi::Abi::Rust, rustc_target::spec::abi::Abi::Rust,
) )
}; };

View file

@ -37,7 +37,7 @@ pub trait Abi<I: Interner<Abi = Self>>: Copy + Debug + Hash + Eq {
fn is_rust(self) -> bool; fn is_rust(self) -> bool;
} }
pub trait Unsafety<I: Interner<Unsafety = Self>>: Copy + Debug + Hash + Eq { pub trait Safety<I: Interner<Safety = Self>>: Copy + Debug + Hash + Eq {
fn prefix_str(self) -> &'static str; fn prefix_str(self) -> &'static str;
} }

View file

@ -58,7 +58,7 @@ pub trait Interner:
type PolyFnSig: Copy + DebugWithInfcx<Self> + Hash + Eq; type PolyFnSig: Copy + DebugWithInfcx<Self> + Hash + Eq;
type AllocId: Copy + Debug + Hash + Eq; type AllocId: Copy + Debug + Hash + Eq;
type Pat: Copy + Debug + Hash + Eq + DebugWithInfcx<Self>; type Pat: Copy + Debug + Hash + Eq + DebugWithInfcx<Self>;
type Unsafety: Unsafety<Self>; type Safety: Safety<Self>;
type Abi: Abi<Self>; type Abi: Abi<Self>;
// Kinds of consts // Kinds of consts

View file

@ -966,7 +966,7 @@ pub struct TypeAndMut<I: Interner> {
pub struct FnSig<I: Interner> { pub struct FnSig<I: Interner> {
pub inputs_and_output: I::Tys, pub inputs_and_output: I::Tys,
pub c_variadic: bool, pub c_variadic: bool,
pub unsafety: I::Unsafety, pub safety: I::Safety,
pub abi: I::Abi, pub abi: I::Abi,
} }
@ -995,9 +995,9 @@ impl<I: Interner> DebugWithInfcx<I> for FnSig<I> {
f: &mut fmt::Formatter<'_>, f: &mut fmt::Formatter<'_>,
) -> fmt::Result { ) -> fmt::Result {
let sig = this.data; let sig = this.data;
let FnSig { inputs_and_output: _, c_variadic, unsafety, abi } = sig; let FnSig { inputs_and_output: _, c_variadic, safety, abi } = sig;
write!(f, "{}", unsafety.prefix_str())?; write!(f, "{}", safety.prefix_str())?;
if !abi.is_rust() { if !abi.is_rust() {
write!(f, "extern \"{abi:?}\" ")?; write!(f, "extern \"{abi:?}\" ")?;
} }

View file

@ -915,8 +915,8 @@ pub enum Mutability {
#[derive(Copy, Clone, Debug, Eq, PartialEq)] #[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Safety { pub enum Safety {
Safe,
Unsafe, Unsafe,
Normal,
} }
#[derive(Copy, Clone, Debug, Eq, PartialEq)] #[derive(Copy, Clone, Debug, Eq, PartialEq)]

View file

@ -1,6 +1,5 @@
use super::{ use super::{
mir::Safety, mir::{Body, Mutability, Safety},
mir::{Body, Mutability},
with, DefId, Error, Symbol, with, DefId, Error, Symbol,
}; };
use crate::abi::Layout; use crate::abi::Layout;
@ -909,7 +908,7 @@ pub type PolyFnSig = Binder<FnSig>;
pub struct FnSig { pub struct FnSig {
pub inputs_and_output: Vec<Ty>, pub inputs_and_output: Vec<Ty>,
pub c_variadic: bool, pub c_variadic: bool,
pub unsafety: Safety, pub safety: Safety,
pub abi: Abi, pub abi: Abi,
} }
@ -1200,7 +1199,7 @@ pub enum TraitSpecializationKind {
#[derive(Clone, Debug, Eq, PartialEq)] #[derive(Clone, Debug, Eq, PartialEq)]
pub struct TraitDecl { pub struct TraitDecl {
pub def_id: TraitDef, pub def_id: TraitDef,
pub unsafety: Safety, pub safety: Safety,
pub paren_sugar: bool, pub paren_sugar: bool,
pub has_auto_impl: bool, pub has_auto_impl: bool,
pub is_marker: bool, pub is_marker: bool,

View file

@ -119,7 +119,7 @@ fn synthesize_auto_trait_impl<'tcx>(
attrs: Default::default(), attrs: Default::default(),
item_id: clean::ItemId::Auto { trait_: trait_def_id, for_: item_def_id }, item_id: clean::ItemId::Auto { trait_: trait_def_id, for_: item_def_id },
kind: Box::new(clean::ImplItem(Box::new(clean::Impl { kind: Box::new(clean::ImplItem(Box::new(clean::Impl {
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
generics, generics,
trait_: Some(clean_trait_ref_with_bindings(cx, trait_ref, ThinVec::new())), trait_: Some(clean_trait_ref_with_bindings(cx, trait_ref, ThinVec::new())),
for_: clean_middle_ty(ty::Binder::dummy(ty), cx, None, None), for_: clean_middle_ty(ty::Binder::dummy(ty), cx, None, None),

View file

@ -87,7 +87,7 @@ pub(crate) fn synthesize_blanket_impls(
attrs: Default::default(), attrs: Default::default(),
item_id: clean::ItemId::Blanket { impl_id: impl_def_id, for_: item_def_id }, item_id: clean::ItemId::Blanket { impl_id: impl_def_id, for_: item_def_id },
kind: Box::new(clean::ImplItem(Box::new(clean::Impl { kind: Box::new(clean::ImplItem(Box::new(clean::Impl {
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
generics: clean_ty_generics( generics: clean_ty_generics(
cx, cx,
tcx.generics_of(impl_def_id), tcx.generics_of(impl_def_id),

View file

@ -613,7 +613,7 @@ pub(crate) fn build_impl(
did, did,
None, None,
clean::ImplItem(Box::new(clean::Impl { clean::ImplItem(Box::new(clean::Impl {
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
generics, generics,
trait_, trait_,
for_, for_,

View file

@ -2077,7 +2077,7 @@ pub(crate) fn clean_middle_ty<'tcx>(
let generic_params = clean_bound_vars(sig.bound_vars()); let generic_params = clean_bound_vars(sig.bound_vars());
BareFunction(Box::new(BareFunctionDecl { BareFunction(Box::new(BareFunctionDecl {
unsafety: sig.unsafety(), safety: sig.safety(),
generic_params, generic_params,
decl, decl,
abi: sig.abi(), abi: sig.abi(),
@ -2565,7 +2565,7 @@ fn clean_bare_fn_ty<'tcx>(
let decl = clean_fn_decl_with_args(cx, bare_fn.decl, None, args); let decl = clean_fn_decl_with_args(cx, bare_fn.decl, None, args);
(generic_params, decl) (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>( pub(crate) fn reexport_chain<'tcx>(
@ -2874,7 +2874,7 @@ fn clean_impl<'tcx>(
}); });
let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| { let mut make_item = |trait_: Option<Path>, for_: Type, items: Vec<Item>| {
let kind = ImplItem(Box::new(Impl { let kind = ImplItem(Box::new(Impl {
unsafety: impl_.unsafety, safety: impl_.safety,
generics: clean_generics(impl_.generics, cx), generics: clean_generics(impl_.generics, cx),
trait_, trait_,
for_, for_,

View file

@ -636,17 +636,17 @@ impl Item {
ty::Asyncness::Yes => hir::IsAsync::Async(DUMMY_SP), ty::Asyncness::Yes => hir::IsAsync::Async(DUMMY_SP),
ty::Asyncness::No => hir::IsAsync::NotAsync, ty::Asyncness::No => hir::IsAsync::NotAsync,
}; };
hir::FnHeader { unsafety: sig.unsafety(), abi: sig.abi(), constness, asyncness } hir::FnHeader { safety: sig.safety(), abi: sig.abi(), constness, asyncness }
} }
let header = match *self.kind { let header = match *self.kind {
ItemKind::ForeignFunctionItem(_) => { ItemKind::ForeignFunctionItem(_) => {
let def_id = self.def_id().unwrap(); let def_id = self.def_id().unwrap();
let abi = tcx.fn_sig(def_id).skip_binder().abi(); let abi = tcx.fn_sig(def_id).skip_binder().abi();
hir::FnHeader { hir::FnHeader {
unsafety: if abi == Abi::RustIntrinsic { safety: if abi == Abi::RustIntrinsic {
intrinsic_operation_unsafety(tcx, def_id.expect_local()) intrinsic_operation_unsafety(tcx, def_id.expect_local())
} else { } else {
hir::Unsafety::Unsafe hir::Safety::Unsafe
}, },
abi, abi,
constness: if abi == Abi::RustIntrinsic constness: if abi == Abi::RustIntrinsic
@ -1448,8 +1448,8 @@ impl Trait {
pub(crate) fn is_notable_trait(&self, tcx: TyCtxt<'_>) -> bool { pub(crate) fn is_notable_trait(&self, tcx: TyCtxt<'_>) -> bool {
tcx.is_doc_notable_trait(self.def_id) tcx.is_doc_notable_trait(self.def_id)
} }
pub(crate) fn unsafety(&self, tcx: TyCtxt<'_>) -> hir::Unsafety { pub(crate) fn safety(&self, tcx: TyCtxt<'_>) -> hir::Safety {
tcx.trait_def(self.def_id).unsafety tcx.trait_def(self.def_id).safety
} }
pub(crate) fn is_object_safe(&self, tcx: TyCtxt<'_>) -> bool { pub(crate) fn is_object_safe(&self, tcx: TyCtxt<'_>) -> bool {
tcx.check_is_object_safe(self.def_id) tcx.check_is_object_safe(self.def_id)
@ -2344,7 +2344,7 @@ pub(crate) struct OpaqueTy {
#[derive(Clone, PartialEq, Eq, Debug, Hash)] #[derive(Clone, PartialEq, Eq, Debug, Hash)]
pub(crate) struct BareFunctionDecl { pub(crate) struct BareFunctionDecl {
pub(crate) unsafety: hir::Unsafety, pub(crate) safety: hir::Safety,
pub(crate) generic_params: Vec<GenericParamDef>, pub(crate) generic_params: Vec<GenericParamDef>,
pub(crate) decl: FnDecl, pub(crate) decl: FnDecl,
pub(crate) abi: Abi, pub(crate) abi: Abi,
@ -2446,7 +2446,7 @@ impl ConstantKind {
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub(crate) struct Impl { pub(crate) struct Impl {
pub(crate) unsafety: hir::Unsafety, pub(crate) safety: hir::Safety,
pub(crate) generics: Generics, pub(crate) generics: Generics,
pub(crate) trait_: Option<Path>, pub(crate) trait_: Option<Path>,
pub(crate) for_: Type, pub(crate) for_: Type,

View file

@ -1013,7 +1013,7 @@ fn fmt_type<'cx>(
} }
clean::BareFunction(ref decl) => { clean::BareFunction(ref decl) => {
print_higher_ranked_params_with_space(&decl.generic_params, cx).fmt(f)?; 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)?; print_abi_with_space(decl.abi).fmt(f)?;
if f.alternate() { if f.alternate() {
f.write_str("fn")?; f.write_str("fn")?;
@ -1303,7 +1303,7 @@ impl clean::Impl {
// Link should match `# Trait implementations` // Link should match `# Trait implementations`
print_higher_ranked_params_with_space(&bare_fn.generic_params, cx).fmt(f)?; 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)?; print_abi_with_space(bare_fn.abi).fmt(f)?;
let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" }; let ellipsis = if bare_fn.decl.c_variadic { ", ..." } else { "" };
primitive_link_fragment( primitive_link_fragment(
@ -1604,11 +1604,11 @@ pub(crate) trait PrintWithSpace {
fn print_with_space(&self) -> &str; fn print_with_space(&self) -> &str;
} }
impl PrintWithSpace for hir::Unsafety { impl PrintWithSpace for hir::Safety {
fn print_with_space(&self) -> &str { fn print_with_space(&self) -> &str {
match self { match self {
hir::Unsafety::Unsafe => "unsafe ", hir::Safety::Unsafe => "unsafe ",
hir::Unsafety::Normal => "", hir::Safety::Safe => "",
} }
} }
} }

View file

@ -934,7 +934,7 @@ fn assoc_method(
RenderMode::ForDeref { .. } => "", RenderMode::ForDeref { .. } => "",
}; };
let asyncness = header.asyncness.print_with_space(); 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 abi = print_abi_with_space(header.abi).to_string();
let href = assoc_href_attr(meth, link, cx); let href = assoc_href_attr(meth, link, cx);
@ -945,7 +945,7 @@ fn assoc_method(
+ defaultness.len() + defaultness.len()
+ constness.len() + constness.len()
+ asyncness.len() + asyncness.len()
+ unsafety.len() + safety.len()
+ abi.len() + abi.len()
+ name.as_str().len() + name.as_str().len()
+ generics_len; + generics_len;
@ -964,14 +964,14 @@ fn assoc_method(
w.reserve(header_len + "<a href=\"\" class=\"fn\">{".len() + "</a>".len()); w.reserve(header_len + "<a href=\"\" class=\"fn\">{".len() + "</a>".len());
write!( write!(
w, w,
"{indent}{vis}{defaultness}{constness}{asyncness}{unsafety}{abi}fn \ "{indent}{vis}{defaultness}{constness}{asyncness}{safety}{abi}fn \
<a{href} class=\"fn\">{name}</a>{generics}{decl}{notable_traits}{where_clause}", <a{href} class=\"fn\">{name}</a>{generics}{decl}{notable_traits}{where_clause}",
indent = indent_str, indent = indent_str,
vis = vis, vis = vis,
defaultness = defaultness, defaultness = defaultness,
constness = constness, constness = constness,
asyncness = asyncness, asyncness = asyncness,
unsafety = unsafety, safety = safety,
abi = abi, abi = abi,
href = href, href = href,
name = name, name = name,

View file

@ -492,7 +492,7 @@ fn item_module(w: &mut Buffer, cx: &mut Context<'_>, item: &clean::Item, items:
let unsafety_flag = match *myitem.kind { let unsafety_flag = match *myitem.kind {
clean::FunctionItem(_) | clean::ForeignFunctionItem(_) clean::FunctionItem(_) | clean::ForeignFunctionItem(_)
if myitem.fn_header(tcx).unwrap().unsafety == hir::Unsafety::Unsafe => if myitem.fn_header(tcx).unwrap().safety == hir::Safety::Unsafe =>
{ {
"<sup title=\"unsafe function\">⚠</sup>" "<sup title=\"unsafe function\">⚠</sup>"
} }
@ -616,7 +616,7 @@ fn item_function(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, f: &cle
let tcx = cx.tcx(); let tcx = cx.tcx();
let header = it.fn_header(tcx).expect("printing a function which isn't a function"); 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 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 abi = print_abi_with_space(header.abi).to_string();
let asyncness = header.asyncness.print_with_space(); let asyncness = header.asyncness.print_with_space();
let visibility = visibility_print_with_space(it, cx).to_string(); 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() + visibility.len()
+ constness.len() + constness.len()
+ asyncness.len() + asyncness.len()
+ unsafety.len() + safety.len()
+ abi.len() + abi.len()
+ name.as_str().len() + name.as_str().len()
+ generics_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); w.reserve(header_len);
write!( write!(
w, w,
"{attrs}{vis}{constness}{asyncness}{unsafety}{abi}fn \ "{attrs}{vis}{constness}{asyncness}{safety}{abi}fn \
{name}{generics}{decl}{notable_traits}{where_clause}", {name}{generics}{decl}{notable_traits}{where_clause}",
attrs = render_attributes_in_pre(it, "", cx), attrs = render_attributes_in_pre(it, "", cx),
vis = visibility, vis = visibility,
constness = constness, constness = constness,
asyncness = asyncness, asyncness = asyncness,
unsafety = unsafety, safety = safety,
abi = abi, abi = abi,
name = name, name = name,
generics = f.generics.print(cx), generics = f.generics.print(cx),
@ -674,10 +674,10 @@ fn item_trait(w: &mut Buffer, cx: &mut Context<'_>, it: &clean::Item, t: &clean:
wrap_item(w, |mut w| { wrap_item(w, |mut w| {
write!( write!(
w, w,
"{attrs}{vis}{unsafety}{is_auto}trait {name}{generics}{bounds}", "{attrs}{vis}{safety}{is_auto}trait {name}{generics}{bounds}",
attrs = render_attributes_in_pre(it, "", cx), attrs = render_attributes_in_pre(it, "", cx),
vis = visibility_print_with_space(it, cx), vis = visibility_print_with_space(it, cx),
unsafety = t.unsafety(tcx).print_with_space(), safety = t.safety(tcx).print_with_space(),
is_auto = if t.is_auto(tcx) { "auto " } else { "" }, is_auto = if t.is_auto(tcx) { "auto " } else { "" },
name = it.name.unwrap(), name = it.name.unwrap(),
generics = t.generics.print(cx), generics = t.generics.print(cx),

View file

@ -619,10 +619,10 @@ impl FromWithTcx<clean::Term> for Term {
impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer { impl FromWithTcx<clean::BareFunctionDecl> for FunctionPointer {
fn from_tcx(bare_decl: clean::BareFunctionDecl, tcx: TyCtxt<'_>) -> Self { 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 { FunctionPointer {
header: Header { header: Header {
unsafe_: matches!(unsafety, rustc_hir::Unsafety::Unsafe), unsafe_: matches!(safety, rustc_hir::Safety::Unsafe),
const_: false, const_: false,
async_: false, async_: false,
abi: convert_abi(abi), abi: convert_abi(abi),
@ -651,7 +651,7 @@ impl FromWithTcx<clean::FnDecl> for FnDecl {
impl FromWithTcx<clean::Trait> for Trait { impl FromWithTcx<clean::Trait> for Trait {
fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self { fn from_tcx(trait_: clean::Trait, tcx: TyCtxt<'_>) -> Self {
let is_auto = trait_.is_auto(tcx); let is_auto = trait_.is_auto(tcx);
let is_unsafe = trait_.unsafety(tcx) == rustc_hir::Unsafety::Unsafe; let is_unsafe = trait_.safety(tcx) == rustc_hir::Safety::Unsafe;
let is_object_safe = trait_.is_object_safe(tcx); let is_object_safe = trait_.is_object_safe(tcx);
let clean::Trait { items, generics, bounds, .. } = trait_; let clean::Trait { items, generics, bounds, .. } = trait_;
Trait { Trait {
@ -678,7 +678,7 @@ impl FromWithTcx<clean::PolyTrait> for PolyTrait {
impl FromWithTcx<clean::Impl> for Impl { impl FromWithTcx<clean::Impl> for Impl {
fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self { fn from_tcx(impl_: clean::Impl, tcx: TyCtxt<'_>) -> Self {
let provided_trait_methods = impl_.provided_trait_methods(tcx); let provided_trait_methods = impl_.provided_trait_methods(tcx);
let clean::Impl { unsafety, generics, trait_, for_, items, polarity, kind } = impl_; let clean::Impl { safety, generics, trait_, for_, items, polarity, kind } = impl_;
// FIXME: use something like ImplKind in JSON? // FIXME: use something like ImplKind in JSON?
let (synthetic, blanket_impl) = match kind { let (synthetic, blanket_impl) = match kind {
clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None), clean::ImplKind::Normal | clean::ImplKind::FakeVariadic => (false, None),
@ -690,7 +690,7 @@ impl FromWithTcx<clean::Impl> for Impl {
ty::ImplPolarity::Negative => true, ty::ImplPolarity::Negative => true,
}; };
Impl { Impl {
is_unsafe: unsafety == rustc_hir::Unsafety::Unsafe, is_unsafe: safety == rustc_hir::Safety::Unsafe,
generics: generics.into_tcx(tcx), generics: generics.into_tcx(tcx),
provided_trait_methods: provided_trait_methods provided_trait_methods: provided_trait_methods
.into_iter() .into_iter()

View file

@ -5,7 +5,7 @@ use rustc_errors::Applicability;
use rustc_hir::def_id::DefId; use rustc_hir::def_id::DefId;
use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, Visitor}; use rustc_hir::intravisit::{walk_expr, walk_fn, walk_item, FnKind, Visitor};
use rustc_hir::{ 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_lint::{LateContext, LateLintPass};
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
@ -415,7 +415,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
} }
if let Some(header) = kind.header() if let Some(header) = kind.header()
&& header.unsafety == Unsafety::Unsafe && header.safety == Safety::Unsafe
{ {
self.has_unsafe = true; self.has_unsafe = true;
} }

View file

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::{span_lint, span_lint_and_note}; use clippy_utils::diagnostics::{span_lint, span_lint_and_note};
use clippy_utils::ty::{implements_trait, is_type_diagnostic_item}; use clippy_utils::ty::{implements_trait, is_type_diagnostic_item};
use clippy_utils::{is_doc_hidden, return_ty}; use clippy_utils::{is_doc_hidden, return_ty};
use rustc_hir::{BodyId, FnSig, OwnerId, Unsafety}; use rustc_hir::{BodyId, FnSig, OwnerId, Safety};
use rustc_lint::LateContext; use rustc_lint::LateContext;
use rustc_middle::ty; use rustc_middle::ty;
use rustc_span::{sym, Span}; use rustc_span::{sym, Span};
@ -33,14 +33,14 @@ pub fn check(
} }
let span = cx.tcx.def_span(owner_id); let span = cx.tcx.def_span(owner_id);
match (headers.safety, sig.header.unsafety) { match (headers.safety, sig.header.safety) {
(false, Unsafety::Unsafe) => span_lint( (false, Safety::Unsafe) => span_lint(
cx, cx,
MISSING_SAFETY_DOC, MISSING_SAFETY_DOC,
span, span,
"unsafe function's docs miss `# Safety` section", "unsafe function's docs miss `# Safety` section",
), ),
(true, Unsafety::Normal) => span_lint( (true, Safety::Safe) => span_lint(
cx, cx,
UNNECESSARY_SAFETY_DOC, UNNECESSARY_SAFETY_DOC,
span, span,

View file

@ -12,7 +12,7 @@ use pulldown_cmark::{BrokenLink, CodeBlockKind, CowStr, Options};
use rustc_ast::ast::Attribute; use rustc_ast::ast::Attribute;
use rustc_data_structures::fx::FxHashSet; use rustc_data_structures::fx::FxHashSet;
use rustc_hir::intravisit::{self, Visitor}; use rustc_hir::intravisit::{self, Visitor};
use rustc_hir::{AnonConst, Expr, ImplItemKind, ItemKind, Node, TraitItemKind, Unsafety}; use rustc_hir::{AnonConst, Expr, ImplItemKind, ItemKind, Node, Safety, TraitItemKind};
use rustc_lint::{LateContext, LateLintPass, LintContext}; use rustc_lint::{LateContext, LateLintPass, LintContext};
use rustc_middle::hir::nested_filter; use rustc_middle::hir::nested_filter;
use rustc_middle::lint::in_external_macro; use rustc_middle::lint::in_external_macro;
@ -415,13 +415,13 @@ impl<'tcx> LateLintPass<'tcx> for Documentation {
} }
}, },
ItemKind::Trait(_, unsafety, ..) => match (headers.safety, unsafety) { ItemKind::Trait(_, unsafety, ..) => match (headers.safety, unsafety) {
(false, Unsafety::Unsafe) => span_lint( (false, Safety::Unsafe) => span_lint(
cx, cx,
MISSING_SAFETY_DOC, MISSING_SAFETY_DOC,
cx.tcx.def_span(item.owner_id), cx.tcx.def_span(item.owner_id),
"docs for unsafe trait missing `# Safety` section", "docs for unsafe trait missing `# Safety` section",
), ),
(true, Unsafety::Normal) => span_lint( (true, Safety::Safe) => span_lint(
cx, cx,
UNNECESSARY_SAFETY_DOC, UNNECESSARY_SAFETY_DOC,
cx.tcx.def_span(item.owner_id), cx.tcx.def_span(item.owner_id),

View file

@ -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::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 clippy_utils::{get_path_from_caller_to_method_type, is_adjusted, path_to_local, path_to_local_id};
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, Param, PatKind, QPath, TyKind, Unsafety}; use rustc_hir::{BindingMode, Expr, ExprKind, FnRetTy, Param, PatKind, QPath, Safety, TyKind};
use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::{LateContext, LateLintPass}; use rustc_lint::{LateContext, LateLintPass};
use rustc_middle::ty::{ use rustc_middle::ty::{
@ -146,7 +146,7 @@ impl<'tcx> LateLintPass<'tcx> for EtaReduction {
ty::FnPtr(sig) => sig.skip_binder(), ty::FnPtr(sig) => sig.skip_binder(),
ty::Closure(_, subs) => cx ty::Closure(_, subs) => cx
.tcx .tcx
.signature_unclosure(subs.as_closure().sig(), Unsafety::Normal) .signature_unclosure(subs.as_closure().sig(), Safety::Safe)
.skip_binder(), .skip_binder(),
_ => { _ => {
if typeck.type_dependent_def_id(body.value.hir_id).is_some() 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 output = typeck.expr_ty(body.value)
&& let ty::Tuple(tys) = *subs.type_at(1).kind() && 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::Safe, Abi::Rust)
} else { } else {
return; return;
} }
@ -241,11 +241,9 @@ fn check_inputs(
} }
fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure: ClosureArgs<'tcx>, call_sig: FnSig<'_>) -> bool { fn check_sig<'tcx>(cx: &LateContext<'tcx>, closure: ClosureArgs<'tcx>, call_sig: FnSig<'_>) -> bool {
call_sig.unsafety == Unsafety::Normal call_sig.safety == Safety::Safe
&& !has_late_bound_to_non_late_bound_regions( && !has_late_bound_to_non_late_bound_regions(
cx.tcx cx.tcx.signature_unclosure(closure.sig(), Safety::Safe).skip_binder(),
.signature_unclosure(closure.sig(), Unsafety::Normal)
.skip_binder(),
call_sig, call_sig,
) )
} }

View file

@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::source::snippet; use clippy_utils::source::snippet;
use rustc_errors::Applicability; use rustc_errors::Applicability;
use rustc_hir::intravisit::FnKind; 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_lint::LateContext;
use rustc_middle::ty; use rustc_middle::ty;
use rustc_span::Span; use rustc_span::Span;
@ -34,7 +34,7 @@ pub fn check_fn(cx: &LateContext<'_>, kind: FnKind<'_>, decl: &FnDecl<'_>, body:
ImplicitSelfKind::None => return, ImplicitSelfKind::None => return,
}; };
let name = if sig.header.unsafety == Unsafety::Unsafe { let name = if sig.header.safety == Safety::Unsafe {
name.strip_suffix("_unchecked").unwrap_or(name) name.strip_suffix("_unchecked").unwrap_or(name)
} else { } else {
name name

View file

@ -19,30 +19,30 @@ pub(super) fn check_fn<'tcx>(
body: &'tcx hir::Body<'tcx>, body: &'tcx hir::Body<'tcx>,
def_id: LocalDefId, def_id: LocalDefId,
) { ) {
let unsafety = match kind { let safety = match kind {
intravisit::FnKind::ItemFn(_, _, hir::FnHeader { unsafety, .. }) => unsafety, intravisit::FnKind::ItemFn(_, _, hir::FnHeader { safety, .. }) => safety,
intravisit::FnKind::Method(_, sig) => sig.header.unsafety, intravisit::FnKind::Method(_, sig) => sig.header.safety,
intravisit::FnKind::Closure => return, 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<'_>) { pub(super) fn check_trait_item<'tcx>(cx: &LateContext<'tcx>, item: &'tcx hir::TraitItem<'_>) {
if let hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(eid)) = item.kind { if let hir::TraitItemKind::Fn(ref sig, hir::TraitFn::Provided(eid)) = item.kind {
let body = cx.tcx.hir().body(eid); let body = cx.tcx.hir().body(eid);
check_raw_ptr(cx, sig.header.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>( fn check_raw_ptr<'tcx>(
cx: &LateContext<'tcx>, cx: &LateContext<'tcx>,
unsafety: hir::Unsafety, safety: hir::Safety,
decl: &'tcx hir::FnDecl<'tcx>, decl: &'tcx hir::FnDecl<'tcx>,
body: &'tcx hir::Body<'tcx>, body: &'tcx hir::Body<'tcx>,
def_id: LocalDefId, def_id: LocalDefId,
) { ) {
if unsafety == hir::Unsafety::Normal && cx.effective_visibilities.is_exported(def_id) { if safety == hir::Safety::Safe && cx.effective_visibilities.is_exported(def_id) {
let raw_ptrs = iter_input_pats(decl, body) let raw_ptrs = iter_input_pats(decl, body)
.filter_map(|arg| raw_ptr_arg(cx, arg)) .filter_map(|arg| raw_ptr_arg(cx, arg))
.collect::<HirIdSet>(); .collect::<HirIdSet>();
@ -58,7 +58,7 @@ fn check_raw_ptr<'tcx>(
}, },
hir::ExprKind::MethodCall(_, recv, args, _) => { hir::ExprKind::MethodCall(_, recv, args, _) => {
let def_id = typeck.type_dependent_def_id(e.hir_id).unwrap(); 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); check_arg(cx, &raw_ptrs, recv);
for arg in args { for arg in args {
check_arg(cx, &raw_ptrs, arg); check_arg(cx, &raw_ptrs, arg);

View file

@ -1,7 +1,7 @@
use clippy_utils::diagnostics::span_lint_and_help; use clippy_utils::diagnostics::span_lint_and_help;
use clippy_utils::ty::{implements_trait, is_type_lang_item}; use clippy_utils::ty::{implements_trait, is_type_lang_item};
use clippy_utils::{return_ty, trait_ref_of_method}; use clippy_utils::{return_ty, trait_ref_of_method};
use rustc_hir::{GenericParamKind, ImplItem, ImplItemKind, LangItem, Unsafety}; use rustc_hir::{GenericParamKind, ImplItem, ImplItemKind, LangItem, Safety};
use rustc_lint::{LateContext, LateLintPass}; use rustc_lint::{LateContext, LateLintPass};
use rustc_session::declare_lint_pass; use rustc_session::declare_lint_pass;
use rustc_span::sym; use rustc_span::sym;
@ -99,7 +99,7 @@ impl<'tcx> LateLintPass<'tcx> for InherentToString {
if let ImplItemKind::Fn(ref signature, _) = impl_item.kind if let ImplItemKind::Fn(ref signature, _) = impl_item.kind
// #11201 // #11201
&& let header = signature.header && let header = signature.header
&& header.unsafety == Unsafety::Normal && header.safety == Safety::Safe
&& header.abi == Abi::Rust && header.abi == Abi::Rust
&& impl_item.ident.name == sym::to_string && impl_item.ident.name == sym::to_string
&& let decl = signature.decl && let decl = signature.decl

View file

@ -5038,7 +5038,7 @@ fn lint_binary_expr_with_method_call(cx: &LateContext<'_>, info: &mut BinaryExpr
} }
const FN_HEADER: hir::FnHeader = hir::FnHeader { const FN_HEADER: hir::FnHeader = hir::FnHeader {
unsafety: hir::Unsafety::Normal, safety: hir::Safety::Safe,
constness: hir::Constness::NotConst, constness: hir::Constness::NotConst,
asyncness: hir::IsAsync::NotAsync, asyncness: hir::IsAsync::NotAsync,
abi: rustc_target::spec::abi::Abi::Rust, abi: rustc_target::spec::abi::Abi::Rust,
@ -5214,7 +5214,5 @@ impl OutType {
} }
fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool { fn fn_header_equals(expected: hir::FnHeader, actual: hir::FnHeader) -> bool {
expected.constness == actual.constness expected.constness == actual.constness && expected.safety == actual.safety && expected.asyncness == actual.asyncness
&& expected.unsafety == actual.unsafety
&& expected.asyncness == actual.asyncness
} }

View file

@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then;
use clippy_utils::visitors::{for_each_expr_with_closures, Descend, Visitable}; use clippy_utils::visitors::{for_each_expr_with_closures, Descend, Visitable};
use core::ops::ControlFlow::Continue; use core::ops::ControlFlow::Continue;
use hir::def::{DefKind, Res}; 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_ast::Mutability;
use rustc_hir as hir; use rustc_hir as hir;
use rustc_lint::{LateContext, LateLintPass}; use rustc_lint::{LateContext, LateLintPass};
@ -133,7 +133,7 @@ fn collect_unsafe_exprs<'tcx>(
ty::FnPtr(sig) => sig, ty::FnPtr(sig) => sig,
_ => return Continue(Descend::Yes), _ => return Continue(Descend::Yes),
}; };
if sig.unsafety() == Unsafety::Unsafe { if sig.safety() == Safety::Unsafe {
unsafe_ops.push(("unsafe function call occurs here", expr.span)); 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) .type_dependent_def_id(expr.hir_id)
.map(|def_id| cx.tcx.fn_sig(def_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)); unsafe_ops.push(("unsafe method call occurs here", expr.span));
} }
} }

View file

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

View file

@ -12,7 +12,7 @@ use rustc_hir::hir_id::{HirId, HirIdMap};
use rustc_hir::intravisit::{walk_expr, Visitor}; use rustc_hir::intravisit::{walk_expr, Visitor};
use rustc_hir::{ use rustc_hir::{
self as hir, AnonConst, BinOpKind, BindingMode, Body, Expr, ExprKind, FnRetTy, FnSig, GenericArg, ImplItemKind, self as hir, AnonConst, BinOpKind, BindingMode, Body, Expr, ExprKind, FnRetTy, FnSig, GenericArg, ImplItemKind,
ItemKind, Lifetime, Mutability, Node, Param, PatKind, QPath, TraitFn, TraitItem, TraitItemKind, TyKind, Unsafety, ItemKind, Lifetime, Mutability, Node, Param, PatKind, QPath, Safety, TraitFn, TraitItem, TraitItemKind, TyKind,
}; };
use rustc_infer::infer::TyCtxtInferExt; use rustc_infer::infer::TyCtxtInferExt;
use rustc_infer::traits::{Obligation, ObligationCause}; use rustc_infer::traits::{Obligation, ObligationCause};
@ -542,7 +542,7 @@ fn check_mut_from_ref<'tcx>(cx: &LateContext<'tcx>, sig: &FnSig<'_>, body: Optio
if let Some(args) = args if let Some(args) = args
&& !args.is_empty() && !args.is_empty()
&& body.map_or(true, |body| { && 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( span_lint_and_then(

View file

@ -200,7 +200,7 @@ impl<'tcx> LateLintPass<'tcx> for UndocumentedUnsafeBlocks {
let item_has_safety_comment = item_has_safety_comment(cx, item); let item_has_safety_comment = item_has_safety_comment(cx, item);
match (&item.kind, item_has_safety_comment) { match (&item.kind, item_has_safety_comment) {
// lint unsafe impl without safety comment // lint unsafe impl without safety comment
(ItemKind::Impl(impl_), HasSafetyComment::No) if impl_.unsafety == hir::Unsafety::Unsafe => { (ItemKind::Impl(impl_), HasSafetyComment::No) if impl_.safety == hir::Safety::Unsafe => {
if !is_lint_allowed(cx, UNDOCUMENTED_UNSAFE_BLOCKS, item.hir_id()) if !is_lint_allowed(cx, UNDOCUMENTED_UNSAFE_BLOCKS, item.hir_id())
&& !is_unsafe_from_proc_macro(cx, item.span) && !is_unsafe_from_proc_macro(cx, item.span)
{ {
@ -222,7 +222,7 @@ impl<'tcx> LateLintPass<'tcx> for UndocumentedUnsafeBlocks {
} }
}, },
// lint safe impl with unnecessary safety comment // lint safe impl with unnecessary safety comment
(ItemKind::Impl(impl_), HasSafetyComment::Yes(pos)) if impl_.unsafety == hir::Unsafety::Normal => { (ItemKind::Impl(impl_), HasSafetyComment::Yes(pos)) if impl_.safety == hir::Safety::Safe => {
if !is_lint_allowed(cx, UNNECESSARY_SAFETY_COMMENT, item.hir_id()) { if !is_lint_allowed(cx, UNNECESSARY_SAFETY_COMMENT, item.hir_id()) {
let (span, help_span) = mk_spans(pos); let (span, help_span) = mk_spans(pos);

View file

@ -386,21 +386,21 @@ pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
( (
Trait(box ast::Trait { Trait(box ast::Trait {
is_auto: la, is_auto: la,
unsafety: lu, safety: lu,
generics: lg, generics: lg,
bounds: lb, bounds: lb,
items: li, items: li,
}), }),
Trait(box ast::Trait { Trait(box ast::Trait {
is_auto: ra, is_auto: ra,
unsafety: ru, safety: ru,
generics: rg, generics: rg,
bounds: rb, bounds: rb,
items: ri, items: ri,
}), }),
) => { ) => {
la == ra la == ra
&& matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No) && matches!(lu, Safety::Default) == matches!(ru, Safety::Default)
&& eq_generics(lg, rg) && eq_generics(lg, rg)
&& over(lb, rb, eq_generic_bound) && over(lb, rb, eq_generic_bound)
&& over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind)) && over(li, ri, |l, r| eq_item(l, r, eq_assoc_item_kind))
@ -408,7 +408,7 @@ pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
(TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, eq_generic_bound), (TraitAlias(lg, lb), TraitAlias(rg, rb)) => eq_generics(lg, rg) && over(lb, rb, eq_generic_bound),
( (
Impl(box ast::Impl { Impl(box ast::Impl {
unsafety: lu, safety: lu,
polarity: lp, polarity: lp,
defaultness: ld, defaultness: ld,
constness: lc, constness: lc,
@ -418,7 +418,7 @@ pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
items: li, items: li,
}), }),
Impl(box ast::Impl { Impl(box ast::Impl {
unsafety: ru, safety: ru,
polarity: rp, polarity: rp,
defaultness: rd, defaultness: rd,
constness: rc, constness: rc,
@ -428,7 +428,7 @@ pub fn eq_item_kind(l: &ItemKind, r: &ItemKind) -> bool {
items: ri, items: ri,
}), }),
) => { ) => {
matches!(lu, Unsafe::No) == matches!(ru, Unsafe::No) matches!(lu, Safety::Default) == matches!(ru, Safety::Default)
&& matches!(lp, ImplPolarity::Positive) == matches!(rp, ImplPolarity::Positive) && matches!(lp, ImplPolarity::Positive) == matches!(rp, ImplPolarity::Positive)
&& eq_defaultness(*ld, *rd) && eq_defaultness(*ld, *rd)
&& matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No) && matches!(lc, ast::Const::No) == matches!(rc, ast::Const::No)
@ -605,7 +605,7 @@ fn eq_opt_coroutine_kind(l: Option<CoroutineKind>, r: Option<CoroutineKind>) ->
} }
pub fn eq_fn_header(l: &FnHeader, r: &FnHeader) -> bool { 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) && eq_opt_coroutine_kind(l.coroutine_kind, r.coroutine_kind)
&& matches!(l.constness, Const::No) == matches!(r.constness, Const::No) && matches!(l.constness, Const::No) == matches!(r.constness, Const::No)
&& eq_ext(&l.ext, &r.ext) && eq_ext(&l.ext, &r.ext)
@ -712,7 +712,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) 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)) => { (BareFn(l), BareFn(r)) => {
l.unsafety == r.unsafety l.safety == r.safety
&& eq_ext(&l.ext, &r.ext) && eq_ext(&l.ext, &r.ext)
&& over(&l.generic_params, &r.generic_params, eq_generic_param) && over(&l.generic_params, &r.generic_params, eq_generic_param)
&& eq_fn_decl(&l.decl, &r.decl) && eq_fn_decl(&l.decl, &r.decl)

View file

@ -18,8 +18,8 @@ use rustc_ast::AttrStyle;
use rustc_hir::intravisit::FnKind; use rustc_hir::intravisit::FnKind;
use rustc_hir::{ use rustc_hir::{
Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, FnRetTy, HirId, Impl, Block, BlockCheckMode, Body, Closure, Destination, Expr, ExprKind, FieldDef, FnHeader, FnRetTy, HirId, Impl,
ImplItem, ImplItemKind, IsAuto, Item, ItemKind, LoopSource, MatchSource, MutTy, Node, QPath, TraitItem, ImplItem, ImplItemKind, IsAuto, Item, ItemKind, LoopSource, MatchSource, MutTy, Node, QPath, Safety, TraitItem,
TraitItemKind, Ty, TyKind, UnOp, UnsafeSource, Unsafety, Variant, VariantData, YieldSource, TraitItemKind, Ty, TyKind, UnOp, UnsafeSource, Variant, VariantData, YieldSource,
}; };
use rustc_lint::{LateContext, LintContext}; use rustc_lint::{LateContext, LintContext};
use rustc_middle::ty::TyCtxt; use rustc_middle::ty::TyCtxt;
@ -207,10 +207,9 @@ fn item_search_pat(item: &Item<'_>) -> (Pat, Pat) {
ItemKind::Struct(VariantData::Struct { .. }, _) => (Pat::Str("struct"), Pat::Str("}")), ItemKind::Struct(VariantData::Struct { .. }, _) => (Pat::Str("struct"), Pat::Str("}")),
ItemKind::Struct(..) => (Pat::Str("struct"), Pat::Str(";")), ItemKind::Struct(..) => (Pat::Str("struct"), Pat::Str(";")),
ItemKind::Union(..) => (Pat::Str("union"), Pat::Str("}")), ItemKind::Union(..) => (Pat::Str("union"), Pat::Str("}")),
ItemKind::Trait(_, Unsafety::Unsafe, ..) ItemKind::Trait(_, Safety::Unsafe, ..)
| ItemKind::Impl(Impl { | ItemKind::Impl(Impl {
unsafety: Unsafety::Unsafe, safety: Safety::Unsafe, ..
..
}) => (Pat::Str("unsafe"), Pat::Str("}")), }) => (Pat::Str("unsafe"), Pat::Str("}")),
ItemKind::Trait(IsAuto::Yes, ..) => (Pat::Str("auto"), Pat::Str("}")), ItemKind::Trait(IsAuto::Yes, ..) => (Pat::Str("auto"), Pat::Str("}")),
ItemKind::Trait(..) => (Pat::Str("trait"), Pat::Str("}")), ItemKind::Trait(..) => (Pat::Str("trait"), Pat::Str("}")),
@ -323,7 +322,7 @@ fn ty_search_pat(ty: &Ty<'_>) -> (Pat, Pat) {
TyKind::Ptr(MutTy { ty, .. }) => (Pat::Str("*"), ty_search_pat(ty).1), TyKind::Ptr(MutTy { ty, .. }) => (Pat::Str("*"), ty_search_pat(ty).1),
TyKind::Ref(_, MutTy { ty, .. }) => (Pat::Str("&"), ty_search_pat(ty).1), TyKind::Ref(_, MutTy { ty, .. }) => (Pat::Str("&"), ty_search_pat(ty).1),
TyKind::BareFn(bare_fn) => ( TyKind::BareFn(bare_fn) => (
if bare_fn.unsafety == Unsafety::Unsafe { if bare_fn.safety == Safety::Unsafe {
Pat::Str("unsafe") Pat::Str("unsafe")
} else if bare_fn.abi != Abi::Rust { } else if bare_fn.abi != Abi::Rust {
Pat::Str("extern") Pat::Str("extern")

View file

@ -1082,7 +1082,7 @@ impl<'a, 'tcx> SpanlessHash<'a, 'tcx> {
mut_ty.mutbl.hash(&mut self.s); mut_ty.mutbl.hash(&mut self.s);
}, },
TyKind::BareFn(bfn) => { TyKind::BareFn(bfn) => {
bfn.unsafety.hash(&mut self.s); bfn.safety.hash(&mut self.s);
bfn.abi.hash(&mut self.s); bfn.abi.hash(&mut self.s);
for arg in bfn.decl.inputs { for arg in bfn.decl.inputs {
self.hash_ty(arg); self.hash_ty(arg);

View file

@ -9,7 +9,7 @@ use rustc_data_structures::fx::{FxHashMap, FxHashSet};
use rustc_hir as hir; use rustc_hir as hir;
use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res}; use rustc_hir::def::{CtorKind, CtorOf, DefKind, Res};
use rustc_hir::def_id::DefId; 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::TyCtxtInferExt; use rustc_infer::infer::TyCtxtInferExt;
use rustc_lint::LateContext; use rustc_lint::LateContext;
use rustc_middle::mir::interpret::Scalar; use rustc_middle::mir::interpret::Scalar;
@ -562,7 +562,7 @@ pub fn peel_mid_ty_refs_is_mutable(ty: Ty<'_>) -> (Ty<'_>, usize, Mutability) {
/// Returns `true` if the given type is an `unsafe` function. /// Returns `true` if the given type is an `unsafe` function.
pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool { pub fn type_is_unsafe_function<'tcx>(cx: &LateContext<'tcx>, ty: Ty<'tcx>) -> bool {
match ty.kind() { 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, _ => false,
} }
} }

Some files were not shown because too many files have changed in this diff Show more