Skip to content

Commit d48af09

Browse files
authored
Rollup merge of #134285 - oli-obk:push-vwrqsqlwnuxo, r=Urgau
Add some convenience helper methods on `hir::Safety` Makes a lot of call sites simpler and should make any refactorings needed for #134090 (comment) simpler, as fewer sites have to be touched in case we end up storing some information in the variants of `hir::Safety`
2 parents 5ce0d81 + 8a4e5d7 commit d48af09

File tree

28 files changed

+74
-70
lines changed

28 files changed

+74
-70
lines changed

Diff for: 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

Diff for: compiler/rustc_const_eval/src/const_eval/fn_queries.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,8 @@ fn is_promotable_const_fn(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
5757
Some(stab) => {
5858
if cfg!(debug_assertions) && stab.promotable {
5959
let sig = tcx.fn_sig(def_id);
60-
assert_eq!(
61-
sig.skip_binder().safety(),
62-
hir::Safety::Safe,
60+
assert!(
61+
sig.skip_binder().safety().is_safe(),
6362
"don't mark const unsafe fns as promotable",
6463
// https://github.com/rust-lang/rust/pull/53851#issuecomment-418760682
6564
);

Diff for: compiler/rustc_hir/src/hir.rs

+14-1
Original file line numberDiff line numberDiff line change
@@ -3434,6 +3434,19 @@ impl Safety {
34343434
Self::Safe => "",
34353435
}
34363436
}
3437+
3438+
#[inline]
3439+
pub fn is_unsafe(self) -> bool {
3440+
!self.is_safe()
3441+
}
3442+
3443+
#[inline]
3444+
pub fn is_safe(self) -> bool {
3445+
match self {
3446+
Self::Unsafe => false,
3447+
Self::Safe => true,
3448+
}
3449+
}
34373450
}
34383451

34393452
impl fmt::Display for Safety {
@@ -3478,7 +3491,7 @@ impl FnHeader {
34783491
}
34793492

34803493
pub fn is_unsafe(&self) -> bool {
3481-
matches!(&self.safety, Safety::Unsafe)
3494+
self.safety.is_unsafe()
34823495
}
34833496
}
34843497

Diff for: 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))

Diff for: 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));

Diff for: compiler/rustc_hir_typeck/src/fallback.rs

+3-3
Original file line numberDiff line numberDiff line change
@@ -762,7 +762,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
762762
if let Some(def_id) = typeck_results.type_dependent_def_id(ex.hir_id)
763763
&& let method_ty = self.fcx.tcx.type_of(def_id).instantiate_identity()
764764
&& let sig = method_ty.fn_sig(self.fcx.tcx)
765-
&& let hir::Safety::Unsafe = sig.safety()
765+
&& sig.safety().is_unsafe()
766766
{
767767
let mut collector = InferVarCollector {
768768
value: (ex.hir_id, ex.span, UnsafeUseReason::Method),
@@ -782,7 +782,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
782782

783783
if func_ty.is_fn()
784784
&& let sig = func_ty.fn_sig(self.fcx.tcx)
785-
&& let hir::Safety::Unsafe = sig.safety()
785+
&& sig.safety().is_unsafe()
786786
{
787787
let mut collector = InferVarCollector {
788788
value: (ex.hir_id, ex.span, UnsafeUseReason::Call),
@@ -813,7 +813,7 @@ fn compute_unsafe_infer_vars<'a, 'tcx>(
813813
// `is_fn` excludes closures, but those can't be unsafe.
814814
if ty.is_fn()
815815
&& let sig = ty.fn_sig(self.fcx.tcx)
816-
&& let hir::Safety::Unsafe = sig.safety()
816+
&& sig.safety().is_unsafe()
817817
{
818818
let mut collector = InferVarCollector {
819819
value: (ex.hir_id, ex.span, UnsafeUseReason::Path),

Diff for: 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

Diff for: 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,
@@ -1281,7 +1281,7 @@ impl VariantDef {
12811281

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

Diff for: 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
}

Diff for: 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();

Diff for: compiler/rustc_passes/src/check_attr.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -715,7 +715,8 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
715715
attrs: &[Attribute],
716716
) {
717717
match target {
718-
Target::Fn => {
718+
Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent)
719+
| Target::Fn => {
719720
// `#[target_feature]` is not allowed in lang items.
720721
if let Some((lang_item, _)) = hir::lang_items::extract(attrs)
721722
// Calling functions with `#[target_feature]` is
@@ -732,7 +733,6 @@ impl<'tcx> CheckAttrVisitor<'tcx> {
732733
});
733734
}
734735
}
735-
Target::Method(MethodKind::Trait { body: true } | MethodKind::Inherent) => {}
736736
// FIXME: #[target_feature] was previously erroneously allowed on statements and some
737737
// crates used this, so only emit a warning.
738738
Target::Statement => {

Diff for: 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 {

Diff for: 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

Diff for: 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

Diff for: 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)

Diff for: 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)))

Diff for: 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 {

Diff for: 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

Diff for: 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

0 commit comments

Comments
 (0)