Skip to content

Commit 8a4e5d7

Browse files
committed
Add some convenience helper methods on hir::Safety
1 parent 3a64bef commit 8a4e5d7

File tree

27 files changed

+72
-68
lines changed

27 files changed

+72
-68
lines changed

compiler/rustc_codegen_ssa/src/codegen_attrs.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rustc_errors::{DiagMessage, SubdiagMessage, struct_span_code_err};
66
use rustc_hir::def::DefKind;
77
use rustc_hir::def_id::{DefId, LOCAL_CRATE, LocalDefId};
88
use rustc_hir::weak_lang_items::WEAK_LANG_ITEMS;
9-
use rustc_hir::{self as hir, HirId, LangItem, lang_items};
9+
use rustc_hir::{HirId, LangItem, lang_items};
1010
use rustc_middle::middle::codegen_fn_attrs::{
1111
CodegenFnAttrFlags, CodegenFnAttrs, PatchableFunctionEntry,
1212
};
@@ -251,7 +251,7 @@ fn codegen_fn_attrs(tcx: TyCtxt<'_>, did: LocalDefId) -> CodegenFnAttrs {
251251
sym::target_feature => {
252252
if !tcx.is_closure_like(did.to_def_id())
253253
&& let Some(fn_sig) = fn_sig()
254-
&& fn_sig.skip_binder().safety() == hir::Safety::Safe
254+
&& fn_sig.skip_binder().safety().is_safe()
255255
{
256256
if tcx.sess.target.is_like_wasm || tcx.sess.opts.actually_rustdoc {
257257
// The `#[target_feature]` attribute is allowed on

compiler/rustc_const_eval/src/const_eval/fn_queries.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -53,9 +53,8 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
5353
Some(stab) => {
5454
if cfg!(debug_assertions) && stab.promotable {
5555
let sig = tcx.fn_sig(def_id);
56-
assert_eq!(
57-
sig.skip_binder().safety(),
58-
hir::Safety::Safe,
56+
assert!(
57+
sig.skip_binder().safety().is_safe(),
5958
"don't mark const unsafe fns as promotable",
6059
// https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682
6160
);

compiler/rustc_hir/src/hir.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -3401,6 +3401,19 @@ impl Safety {
34013401
Self::Safe => "",
34023402
}
34033403
}
3404+
3405+
#[inline]
3406+
pub fn is_unsafe(self) -> bool {
3407+
!self.is_safe()
3408+
}
3409+
3410+
#[inline]
3411+
pub fn is_safe(self) -> bool {
3412+
match self {
3413+
Self::Unsafe => false,
3414+
Self::Safe => true,
3415+
}
3416+
}
34043417
}
34053418

34063419
impl fmt::Display for Safety {
@@ -3445,7 +3458,7 @@ impl FnHeader {
34453458
}
34463459

34473460
pub fn is_unsafe(&self) -> bool {
3448-
matches!(&self.safety, Safety::Unsafe)
3461+
self.safety.is_unsafe()
34493462
}
34503463
}
34513464

compiler/rustc_hir_analysis/src/check/check.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@ use rustc_data_structures::unord::{UnordMap, UnordSet};
66
use rustc_errors::MultiSpan;
77
use rustc_errors::codes::*;
88
use rustc_hir::def::{CtorKind, DefKind};
9-
use rustc_hir::{Node, Safety, intravisit};
9+
use rustc_hir::{Node, intravisit};
1010
use rustc_infer::infer::{RegionVariableOrigin, TyCtxtInferExt};
1111
use rustc_infer::traits::{Obligation, ObligationCauseCode};
1212
use rustc_lint_defs::builtin::{
@@ -161,7 +161,7 @@ fn check_unsafe_fields(tcx: TyCtxt<'_>, item_def_id: LocalDefId) {
161161
};
162162
let typing_env = ty::TypingEnv::non_body_analysis(tcx, item_def_id);
163163
for field in def.all_fields() {
164-
if field.safety != Safety::Unsafe {
164+
if !field.safety.is_unsafe() {
165165
continue;
166166
}
167167
let Ok(field_ty) = tcx.try_normalize_erasing_regions(typing_env, field.ty(tcx, args))

compiler/rustc_hir_typeck/src/coercion.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -863,7 +863,8 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
863863
let outer_universe = self.infcx.universe();
864864

865865
let result = if let ty::FnPtr(_, hdr_b) = b.kind()
866-
&& let (hir::Safety::Safe, hir::Safety::Unsafe) = (fn_ty_a.safety(), hdr_b.safety)
866+
&& fn_ty_a.safety().is_safe()
867+
&& hdr_b.safety.is_unsafe()
867868
{
868869
let unsafe_a = self.tcx.safe_to_unsafe_fn_ty(fn_ty_a);
869870
self.unify_and(unsafe_a, b, to_unsafe)
@@ -925,7 +926,7 @@ impl<'f, 'tcx> Coerce<'f, 'tcx> {
925926

926927
// Safe `#[target_feature]` functions are not assignable to safe fn pointers (RFC 2396).
927928

928-
if b_hdr.safety == hir::Safety::Safe
929+
if b_hdr.safety.is_safe()
929930
&& !self.tcx.codegen_fn_attrs(def_id).target_features.is_empty()
930931
{
931932
return Err(TypeError::TargetFeatureCast(def_id));

compiler/rustc_hir_typeck/src/fallback.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -765,7 +765,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
765765
if let Some(def_id) = typeck_results.type_dependent_def_id(ex.hir_id)
766766
&& let method_ty = self.fcx.tcx.type_of(def_id).instantiate_identity()
767767
&& let sig = method_ty.fn_sig(self.fcx.tcx)
768-
&& let hir::Safety::Unsafe = sig.safety()
768+
&& sig.safety().is_unsafe()
769769
{
770770
let mut collector = InferVarCollector {
771771
value: (ex.hir_id, ex.span, UnsafeUseReason::Method),
@@ -785,7 +785,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
785785

786786
if func_ty.is_fn()
787787
&& let sig = func_ty.fn_sig(self.fcx.tcx)
788-
&& let hir::Safety::Unsafe = sig.safety()
788+
&& sig.safety().is_unsafe()
789789
{
790790
let mut collector = InferVarCollector {
791791
value: (ex.hir_id, ex.span, UnsafeUseReason::Call),
@@ -816,7 +816,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
816816
// `is_fn` excludes closures, but those can't be unsafe.
817817
if ty.is_fn()
818818
&& let sig = ty.fn_sig(self.fcx.tcx)
819-
&& let hir::Safety::Unsafe = sig.safety()
819+
&& sig.safety().is_unsafe()
820820
{
821821
let mut collector = InferVarCollector {
822822
value: (ex.hir_id, ex.span, UnsafeUseReason::Path),

compiler/rustc_middle/src/ty/context.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -586,7 +586,7 @@ impl<'tcx> Interner for TyCtxt<'tcx> {
586586
}
587587

588588
fn trait_is_unsafe(self, trait_def_id: Self::DefId) -> bool {
589-
self.trait_def(trait_def_id).safety == hir::Safety::Unsafe
589+
self.trait_def(trait_def_id).safety.is_unsafe()
590590
}
591591

592592
fn is_impl_trait_in_trait(self, def_id: DefId) -> bool {
@@ -722,7 +722,7 @@ impl<'tcx> rustc_type_ir::inherent::Safety<TyCtxt<'tcx>> for hir::Safety {
722722
}
723723

724724
fn is_safe(self) -> bool {
725-
matches!(self, hir::Safety::Safe)
725+
self.is_safe()
726726
}
727727

728728
fn prefix_str(self) -> &'static str {
@@ -2521,7 +2521,7 @@ impl<'tcx> TyCtxt<'tcx> {
25212521
/// that is, a `fn` type that is equivalent in every way for being
25222522
/// unsafe.
25232523
pub fn safe_to_unsafe_fn_ty(self, sig: PolyFnSig<'tcx>) -> Ty<'tcx> {
2524-
assert_eq!(sig.safety(), hir::Safety::Safe);
2524+
assert!(sig.safety().is_safe());
25252525
Ty::new_fn_ptr(self, sig.map_bound(|sig| ty::FnSig { safety: hir::Safety::Unsafe, ..sig }))
25262526
}
25272527

compiler/rustc_middle/src/ty/mod.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -33,9 +33,9 @@ use rustc_data_structures::intern::Interned;
3333
use rustc_data_structures::stable_hasher::{HashStable, StableHasher};
3434
use rustc_data_structures::steal::Steal;
3535
use rustc_errors::{Diag, ErrorGuaranteed, StashKey};
36+
use rustc_hir::LangItem;
3637
use rustc_hir::def::{CtorKind, CtorOf, DefKind, DocLinkResMap, LifetimeRes, Res};
3738
use rustc_hir::def_id::{CrateNum, DefId, DefIdMap, LocalDefId, LocalDefIdMap};
38-
use rustc_hir::{LangItem, Safety};
3939
use rustc_index::IndexVec;
4040
use rustc_macros::{
4141
Decodable, Encodable, HashStable, TyDecodable, TyEncodable, TypeFoldable, TypeVisitable,
@@ -1279,7 +1279,7 @@ impl VariantDef {
12791279

12801280
/// Returns whether this variant has unsafe fields.
12811281
pub fn has_unsafe_fields(&self) -> bool {
1282-
self.fields.iter().any(|x| x.safety == Safety::Unsafe)
1282+
self.fields.iter().any(|x| x.safety.is_unsafe())
12831283
}
12841284
}
12851285

compiler/rustc_middle/src/ty/util.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -1291,7 +1291,7 @@ impl<'tcx> Ty<'tcx> {
12911291
/// Checks whether this type is an ADT that has unsafe fields.
12921292
pub fn has_unsafe_fields(self) -> bool {
12931293
if let ty::Adt(adt_def, ..) = self.kind() {
1294-
adt_def.all_fields().any(|x| x.safety == hir::Safety::Unsafe)
1294+
adt_def.all_fields().any(|x| x.safety.is_unsafe())
12951295
} else {
12961296
false
12971297
}

compiler/rustc_mir_build/src/check_unsafety.rs

+6-10
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use std::ops::Bound;
44

55
use rustc_errors::DiagArgValue;
66
use rustc_hir::def::DefKind;
7-
use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability, Safety};
7+
use rustc_hir::{self as hir, BindingMode, ByRef, HirId, Mutability};
88
use rustc_middle::middle::codegen_fn_attrs::TargetFeature;
99
use rustc_middle::mir::BorrowKind;
1010
use rustc_middle::span_bug;
@@ -342,7 +342,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
342342
PatKind::Leaf { subpatterns, .. } => {
343343
if let ty::Adt(adt_def, ..) = pat.ty.kind() {
344344
for pat in subpatterns {
345-
if adt_def.non_enum_variant().fields[pat.field].safety == Safety::Unsafe {
345+
if adt_def.non_enum_variant().fields[pat.field].safety.is_unsafe() {
346346
self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
347347
}
348348
}
@@ -367,7 +367,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
367367
PatKind::Variant { adt_def, args: _, variant_index, subpatterns } => {
368368
for pat in subpatterns {
369369
let field = &pat.field;
370-
if adt_def.variant(*variant_index).fields[*field].safety == Safety::Unsafe {
370+
if adt_def.variant(*variant_index).fields[*field].safety.is_unsafe() {
371371
self.requires_unsafe(pat.pattern.span, UseOfUnsafeField);
372372
}
373373
}
@@ -479,7 +479,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
479479
return; // don't visit the whole expression
480480
}
481481
ExprKind::Call { fun, ty: _, args: _, from_hir_call: _, fn_span: _ } => {
482-
if self.thir[fun].ty.fn_sig(self.tcx).safety() == hir::Safety::Unsafe {
482+
if self.thir[fun].ty.fn_sig(self.tcx).safety().is_unsafe() {
483483
let func_id = if let ty::FnDef(func_id, _) = self.thir[fun].ty.kind() {
484484
Some(*func_id)
485485
} else {
@@ -623,7 +623,7 @@ impl<'a, 'tcx> Visitor<'a, 'tcx> for UnsafetyVisitor<'a, 'tcx> {
623623
ExprKind::Field { lhs, variant_index, name } => {
624624
let lhs = &self.thir[lhs];
625625
if let ty::Adt(adt_def, _) = lhs.ty.kind() {
626-
if adt_def.variant(variant_index).fields[name].safety == Safety::Unsafe {
626+
if adt_def.variant(variant_index).fields[name].safety.is_unsafe() {
627627
self.requires_unsafe(expr.span, UseOfUnsafeField);
628628
} else if adt_def.is_union() {
629629
if let Some(assigned_ty) = self.assignment_info {
@@ -1112,11 +1112,7 @@ pub(crate) fn check_unsafety(tcx: TyCtxt<'_>, def: LocalDefId) {
11121112

11131113
let hir_id = tcx.local_def_id_to_hir_id(def);
11141114
let safety_context = tcx.hir().fn_sig_by_hir_id(hir_id).map_or(SafetyContext::Safe, |fn_sig| {
1115-
if fn_sig.header.safety == hir::Safety::Unsafe {
1116-
SafetyContext::UnsafeFn
1117-
} else {
1118-
SafetyContext::Safe
1119-
}
1115+
if fn_sig.header.safety.is_unsafe() { SafetyContext::UnsafeFn } else { SafetyContext::Safe }
11201116
});
11211117
let body_target_features = &tcx.body_codegen_attrs(def.to_def_id()).target_features;
11221118
let mut warnings = Vec::new();

compiler/rustc_symbol_mangling/src/v0.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -439,7 +439,7 @@ impl<'tcx> Printer<'tcx> for SymbolMangler<'tcx> {
439439
let sig = sig_tys.with(hdr);
440440
self.push("F");
441441
self.in_binder(&sig, |cx, sig| {
442-
if sig.safety == hir::Safety::Unsafe {
442+
if sig.safety.is_unsafe() {
443443
cx.push("U");
444444
}
445445
match sig.abi {

compiler/rustc_trait_selection/src/traits/misc.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,7 @@ pub fn type_allowed_to_implement_copy<'tcx>(
8484
return Err(CopyImplementationError::HasDestructor);
8585
}
8686

87-
if impl_safety == hir::Safety::Safe && self_type.has_unsafe_fields() {
87+
if impl_safety.is_safe() && self_type.has_unsafe_fields() {
8888
return Err(CopyImplementationError::HasUnsafeFields);
8989
}
9090

src/librustdoc/html/format.rs

+1-4
Original file line numberDiff line numberDiff line change
@@ -1626,10 +1626,7 @@ pub(crate) trait PrintWithSpace {
16261626

16271627
impl PrintWithSpace for hir::Safety {
16281628
fn print_with_space(&self) -> &str {
1629-
match self {
1630-
hir::Safety::Unsafe => "unsafe ",
1631-
hir::Safety::Safe => "",
1632-
}
1629+
self.prefix_str()
16331630
}
16341631
}
16351632

src/librustdoc/html/render/print_item.rs

+2-4
Original file line numberDiff line numberDiff line change
@@ -469,7 +469,7 @@ fn item_module(w: &mut Buffer, cx: &Context<'_>, item: &clean::Item, items: &[cl
469469

470470
let unsafety_flag = match myitem.kind {
471471
clean::FunctionItem(_) | clean::ForeignFunctionItem(..)
472-
if myitem.fn_header(tcx).unwrap().safety == hir::Safety::Unsafe =>
472+
if myitem.fn_header(tcx).unwrap().safety.is_unsafe() =>
473473
{
474474
"<sup title=\"unsafe function\">⚠</sup>"
475475
}
@@ -1926,9 +1926,7 @@ fn item_static(
19261926
buffer,
19271927
"{vis}{safe}static {mutability}{name}: {typ}",
19281928
vis = visibility_print_with_space(it, cx),
1929-
safe = safety
1930-
.map(|safe| if safe == hir::Safety::Unsafe { "unsafe " } else { "" })
1931-
.unwrap_or(""),
1929+
safe = safety.map(|safe| safe.prefix_str()).unwrap_or(""),
19321930
mutability = s.mutability.print_with_space(),
19331931
name = it.name.unwrap(),
19341932
typ = s.type_.print(cx)

src/librustdoc/json/conversions.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -639,7 +639,7 @@ impl FromClean<clean::BareFunctionDecl> for FunctionPointer {
639639
let clean::BareFunctionDecl { safety, generic_params, decl, abi } = bare_decl;
640640
FunctionPointer {
641641
header: FunctionHeader {
642-
is_unsafe: matches!(safety, rustc_hir::Safety::Unsafe),
642+
is_unsafe: safety.is_unsafe(),
643643
is_const: false,
644644
is_async: false,
645645
abi: convert_abi(abi),
@@ -669,7 +669,7 @@ impl FromClean<clean::Trait> for Trait {
669669
fn from_clean(trait_: clean::Trait, renderer: &JsonRenderer<'_>) -> Self {
670670
let tcx = renderer.tcx;
671671
let is_auto = trait_.is_auto(tcx);
672-
let is_unsafe = trait_.safety(tcx) == rustc_hir::Safety::Unsafe;
672+
let is_unsafe = trait_.safety(tcx).is_unsafe();
673673
let is_dyn_compatible = trait_.is_dyn_compatible(tcx);
674674
let clean::Trait { items, generics, bounds, .. } = trait_;
675675
Trait {
@@ -711,7 +711,7 @@ impl FromClean<clean::Impl> for Impl {
711711
ty::ImplPolarity::Negative => true,
712712
};
713713
Impl {
714-
is_unsafe: safety == rustc_hir::Safety::Unsafe,
714+
is_unsafe: safety.is_unsafe(),
715715
generics: generics.into_json(renderer),
716716
provided_trait_methods: provided_trait_methods
717717
.into_iter()
@@ -840,7 +840,7 @@ fn convert_static(
840840
Static {
841841
type_: (*stat.type_).into_json(renderer),
842842
is_mutable: stat.mutability == ast::Mutability::Mut,
843-
is_unsafe: safety == rustc_hir::Safety::Unsafe,
843+
is_unsafe: safety.is_unsafe(),
844844
expr: stat
845845
.expr
846846
.map(|e| rendered_const(tcx, tcx.hir().body(e), tcx.hir().body_owner_def_id(e)))

src/tools/clippy/clippy_lints/src/derive.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use rustc_errors::Applicability;
77
use rustc_hir::def_id::DefId;
88
use rustc_hir::intravisit::{FnKind, Visitor, walk_expr, walk_fn, walk_item};
99
use rustc_hir::{
10-
self as hir, BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, Impl, Item, ItemKind, Safety, UnsafeSource,
10+
self as hir, BlockCheckMode, BodyId, Expr, ExprKind, FnDecl, Impl, Item, ItemKind, UnsafeSource,
1111
};
1212
use rustc_lint::{LateContext, LateLintPass};
1313
use rustc_middle::hir::nested_filter;
@@ -421,7 +421,7 @@ impl<'tcx> Visitor<'tcx> for UnsafeVisitor<'_, 'tcx> {
421421
id: LocalDefId,
422422
) -> Self::Result {
423423
if let Some(header) = kind.header()
424-
&& header.safety == Safety::Unsafe
424+
&& header.safety.is_unsafe()
425425
{
426426
ControlFlow::Break(())
427427
} else {

src/tools/clippy/clippy_lints/src/eta_reduction.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -281,7 +281,7 @@ fn check_inputs(
281281
}
282282

283283
fn check_sig<'tcx>(closure_sig: FnSig<'tcx>, call_sig: FnSig<'tcx>) -> bool {
284-
call_sig.safety == Safety::Safe && !has_late_bound_to_non_late_bound_regions(closure_sig, call_sig)
284+
call_sig.safety.is_safe() && !has_late_bound_to_non_late_bound_regions(closure_sig, call_sig)
285285
}
286286

287287
/// This walks through both signatures and checks for any time a late-bound region is expected by an

src/tools/clippy/clippy_lints/src/functions/misnamed_getters.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use clippy_utils::diagnostics::span_lint_and_then;
22
use clippy_utils::source::snippet;
33
use rustc_errors::Applicability;
44
use rustc_hir::intravisit::FnKind;
5-
use rustc_hir::{Body, ExprKind, FnDecl, ImplicitSelfKind, Safety};
5+
use rustc_hir::{Body, ExprKind, FnDecl, ImplicitSelfKind};
66
use rustc_lint::LateContext;
77
use rustc_middle::ty;
88
use rustc_span::Span;
@@ -34,7 +34,7 @@ pub fn check_fn(cx: &LateContext<'_>, kind: FnKind<'_>, decl: &FnDecl<'_>, body:
3434
ImplicitSelfKind::None => return,
3535
};
3636

37-
let name = if sig.header.safety == Safety::Unsafe {
37+
let name = if sig.header.safety.is_unsafe() {
3838
name.strip_suffix("_unchecked").unwrap_or(name)
3939
} else {
4040
name

src/tools/clippy/clippy_lints/src/functions/not_unsafe_ptr_arg_deref.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ fn check_raw_ptr<'tcx>(
4242
body: &'tcx hir::Body<'tcx>,
4343
def_id: LocalDefId,
4444
) {
45-
if safety == hir::Safety::Safe && cx.effective_visibilities.is_exported(def_id) {
45+
if safety.is_safe() && cx.effective_visibilities.is_exported(def_id) {
4646
let raw_ptrs = iter_input_pats(decl, body)
4747
.filter_map(|arg| raw_ptr_arg(cx, arg))
4848
.collect::<HirIdSet>();
@@ -58,7 +58,7 @@ fn check_raw_ptr<'tcx>(
5858
},
5959
hir::ExprKind::MethodCall(_, recv, args, _) => {
6060
let def_id = typeck.type_dependent_def_id(e.hir_id).unwrap();
61-
if cx.tcx.fn_sig(def_id).skip_binder().skip_binder().safety == hir::Safety::Unsafe {
61+
if cx.tcx.fn_sig(def_id).skip_binder().skip_binder().safety.is_unsafe() {
6262
check_arg(cx, &raw_ptrs, recv);
6363
for arg in args {
6464
check_arg(cx, &raw_ptrs, arg);

0 commit comments

Comments
 (0)