Skip to content

Commit 2cda185

Browse files
veluca93jhpratt
andcommitted
Draft implementation of the unsafe-fields RFC.
Co-Authored-By: Jacob Pratt <[email protected]>
1 parent d4822c2 commit 2cda185

File tree

29 files changed

+419
-50
lines changed

29 files changed

+419
-50
lines changed

compiler/rustc_ast/src/ast.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3036,6 +3036,7 @@ pub struct FieldDef {
30363036
pub id: NodeId,
30373037
pub span: Span,
30383038
pub vis: Visibility,
3039+
pub safety: Safety,
30393040
pub ident: Option<Ident>,
30403041

30413042
pub ty: P<Ty>,

compiler/rustc_ast/src/mut_visit.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -1044,10 +1044,11 @@ pub fn walk_flat_map_field_def<T: MutVisitor>(
10441044
visitor: &mut T,
10451045
mut fd: FieldDef,
10461046
) -> SmallVec<[FieldDef; 1]> {
1047-
let FieldDef { span, ident, vis, id, ty, attrs, is_placeholder: _ } = &mut fd;
1047+
let FieldDef { span, ident, vis, id, ty, attrs, is_placeholder: _, safety } = &mut fd;
10481048
visitor.visit_id(id);
10491049
visit_attrs(visitor, attrs);
10501050
visitor.visit_vis(vis);
1051+
visit_safety(visitor, safety);
10511052
visit_opt(ident, |ident| visitor.visit_ident(ident));
10521053
visitor.visit_ty(ty);
10531054
visitor.visit_span(span);

compiler/rustc_ast/src/visit.rs

+1-1
Original file line numberDiff line numberDiff line change
@@ -929,7 +929,7 @@ pub fn walk_struct_def<'a, V: Visitor<'a>>(
929929
}
930930

931931
pub fn walk_field_def<'a, V: Visitor<'a>>(visitor: &mut V, field: &'a FieldDef) -> V::Result {
932-
let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _ } = field;
932+
let FieldDef { attrs, id: _, span: _, vis, ident, ty, is_placeholder: _, safety: _ } = field;
933933
walk_list!(visitor, visit_attribute, attrs);
934934
try_visit!(visitor.visit_vis(vis));
935935
visit_opt!(visitor, visit_ident, ident);

compiler/rustc_ast_lowering/src/item.rs

+1
Original file line numberDiff line numberDiff line change
@@ -724,6 +724,7 @@ impl<'hir> LoweringContext<'_, 'hir> {
724724
},
725725
vis_span: self.lower_span(f.vis.span),
726726
ty,
727+
safety: self.lower_safety(f.safety, hir::Safety::Safe),
727728
}
728729
}
729730

compiler/rustc_ast_passes/src/feature_gate.rs

+1
Original file line numberDiff line numberDiff line change
@@ -548,6 +548,7 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
548548
gate_all!(global_registration, "global registration is experimental");
549549
gate_all!(return_type_notation, "return type notation is experimental");
550550
gate_all!(pin_ergonomics, "pinned reference syntax is experimental");
551+
gate_all!(unsafe_fields, "`unsafe` fields are experimental");
551552

552553
if !visitor.features.never_patterns() {
553554
if let Some(spans) = spans.get(&sym::never_patterns) {

compiler/rustc_expand/src/placeholders.rs

+2-1
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ use rustc_ast::mut_visit::*;
22
use rustc_ast::ptr::P;
33
use rustc_ast::token::Delimiter;
44
use rustc_ast::visit::AssocCtxt;
5-
use rustc_ast::{self as ast};
5+
use rustc_ast::{self as ast, Safety};
66
use rustc_data_structures::fx::FxHashMap;
77
use rustc_span::DUMMY_SP;
88
use rustc_span::symbol::Ident;
@@ -173,6 +173,7 @@ pub(crate) fn placeholder(
173173
ty: ty(),
174174
vis,
175175
is_placeholder: true,
176+
safety: Safety::Default,
176177
}]),
177178
AstFragmentKind::Variants => AstFragment::Variants(smallvec![ast::Variant {
178179
attrs: Default::default(),

compiler/rustc_feature/src/unstable.rs

+2
Original file line numberDiff line numberDiff line change
@@ -623,6 +623,8 @@ declare_features! (
623623
/// Allows creation of instances of a struct by moving fields that have
624624
/// not changed from prior instances of the same struct (RFC #2528)
625625
(unstable, type_changing_struct_update, "1.58.0", Some(86555)),
626+
/// Allows declaring fields `unsafe`.
627+
(unstable, unsafe_fields, "CURRENT_RUSTC_VERSION", Some(1234567)), // FIXME: proper tracking issue.
626628
/// Allows const generic parameters to be defined with types that
627629
/// are not `Sized`, e.g. `fn foo<const N: [u8]>() {`.
628630
(incomplete, unsized_const_params, "1.82.0", Some(95174)),

compiler/rustc_hir/src/hir.rs

+1
Original file line numberDiff line numberDiff line change
@@ -3177,6 +3177,7 @@ pub struct FieldDef<'hir> {
31773177
pub hir_id: HirId,
31783178
pub def_id: LocalDefId,
31793179
pub ty: &'hir Ty<'hir>,
3180+
pub safety: Safety,
31803181
}
31813182

31823183
impl FieldDef<'_> {

compiler/rustc_hir_analysis/src/collect.rs

+1
Original file line numberDiff line numberDiff line change
@@ -1031,6 +1031,7 @@ fn lower_variant(
10311031
did: f.def_id.to_def_id(),
10321032
name: f.ident.name,
10331033
vis: tcx.visibility(f.def_id),
1034+
safety: f.safety,
10341035
})
10351036
.collect();
10361037
let recovered = match def {

compiler/rustc_metadata/src/rmeta/decoder.rs

+6
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ use rustc_data_structures::sync::{Lock, Lrc, OnceLock};
1515
use rustc_data_structures::unhash::UnhashMap;
1616
use rustc_expand::base::{SyntaxExtension, SyntaxExtensionKind};
1717
use rustc_expand::proc_macro::{AttrProcMacro, BangProcMacro, DeriveProcMacro};
18+
use rustc_hir::Safety;
1819
use rustc_hir::def::Res;
1920
use rustc_hir::def_id::{CRATE_DEF_INDEX, LOCAL_CRATE};
2021
use rustc_hir::definitions::{DefPath, DefPathData};
@@ -1101,6 +1102,7 @@ impl<'a> CrateMetadataRef<'a> {
11011102
did,
11021103
name: self.item_name(did.index),
11031104
vis: self.get_visibility(did.index),
1105+
safety: self.get_safety(did.index),
11041106
})
11051107
.collect(),
11061108
adt_kind,
@@ -1162,6 +1164,10 @@ impl<'a> CrateMetadataRef<'a> {
11621164
.map_id(|index| self.local_def_id(index))
11631165
}
11641166

1167+
fn get_safety(self, id: DefIndex) -> Safety {
1168+
self.root.tables.safety.get(self, id).unwrap_or_else(|| self.missing("safety", id))
1169+
}
1170+
11651171
fn get_trait_item_def_id(self, id: DefIndex) -> Option<DefId> {
11661172
self.root.tables.trait_item_def_id.get(self, id).map(|d| d.decode_from_cdata(self))
11671173
}

compiler/rustc_metadata/src/rmeta/encoder.rs

+5
Original file line numberDiff line numberDiff line change
@@ -1595,6 +1595,11 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
15951595
f.did.index
15961596
}));
15971597

1598+
for field in &variant.fields {
1599+
// FIXME: this probably blows up rmeta size.
1600+
self.tables.safety.set_some(field.did.index, field.safety);
1601+
}
1602+
15981603
if let Some((CtorKind::Fn, ctor_def_id)) = variant.ctor {
15991604
let fn_sig = tcx.fn_sig(ctor_def_id);
16001605
// FIXME only encode signature for ctor_def_id

compiler/rustc_metadata/src/rmeta/mod.rs

+1
Original file line numberDiff line numberDiff line change
@@ -411,6 +411,7 @@ define_tables! {
411411
associated_item_or_field_def_ids: Table<DefIndex, LazyArray<DefIndex>>,
412412
def_kind: Table<DefIndex, DefKind>,
413413
visibility: Table<DefIndex, LazyValue<ty::Visibility<DefIndex>>>,
414+
safety: Table<DefIndex, hir::Safety>,
414415
def_span: Table<DefIndex, LazyValue<Span>>,
415416
def_ident_span: Table<DefIndex, LazyValue<Span>>,
416417
lookup_stability: Table<DefIndex, LazyValue<attr::Stability>>,

compiler/rustc_metadata/src/rmeta/table.rs

+7
Original file line numberDiff line numberDiff line change
@@ -198,6 +198,13 @@ fixed_size_enum! {
198198
}
199199
}
200200

201+
fixed_size_enum! {
202+
hir::Safety {
203+
( Unsafe )
204+
( Safe )
205+
}
206+
}
207+
201208
fixed_size_enum! {
202209
ty::Asyncness {
203210
( Yes )

compiler/rustc_middle/src/ty/mod.rs

+6-4
Original file line numberDiff line numberDiff line change
@@ -1357,6 +1357,7 @@ pub struct FieldDef {
13571357
pub did: DefId,
13581358
pub name: Symbol,
13591359
pub vis: Visibility<DefId>,
1360+
pub safety: hir::Safety,
13601361
}
13611362

13621363
impl PartialEq for FieldDef {
@@ -1369,15 +1370,16 @@ impl PartialEq for FieldDef {
13691370
// of `FieldDef` changes, a compile-error will be produced, reminding
13701371
// us to revisit this assumption.
13711372

1372-
let Self { did: lhs_did, name: _, vis: _ } = &self;
1373+
let Self { did: lhs_did, name: _, vis: _, safety: _ } = &self;
13731374

1374-
let Self { did: rhs_did, name: _, vis: _ } = other;
1375+
let Self { did: rhs_did, name: _, vis: _, safety: _ } = other;
13751376

13761377
let res = lhs_did == rhs_did;
13771378

13781379
// Double check that implicit assumption detailed above.
13791380
if cfg!(debug_assertions) && res {
1380-
let deep = self.name == other.name && self.vis == other.vis;
1381+
let deep =
1382+
self.name == other.name && self.vis == other.vis && self.safety == other.safety;
13811383
assert!(deep, "FieldDef for the same def-id has differing data");
13821384
}
13831385

@@ -1397,7 +1399,7 @@ impl Hash for FieldDef {
13971399
// of `FieldDef` changes, a compile-error will be produced, reminding
13981400
// us to revisit this assumption.
13991401

1400-
let Self { did, name: _, vis: _ } = &self;
1402+
let Self { did, name: _, vis: _, safety: _ } = &self;
14011403

14021404
did.hash(s)
14031405
}

compiler/rustc_middle/src/ty/parameterized.rs

+1
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ trivially_parameterized_over_tcx! {
8686
rustc_attr::Stability,
8787
rustc_hir::Constness,
8888
rustc_hir::Defaultness,
89+
rustc_hir::Safety,
8990
rustc_hir::CoroutineKind,
9091
rustc_hir::IsAsync,
9192
rustc_hir::LangItem,

compiler/rustc_mir_build/messages.ftl

+30
Original file line numberDiff line numberDiff line change
@@ -125,6 +125,16 @@ mir_build_initializing_type_with_requires_unsafe_unsafe_op_in_unsafe_fn_allowed
125125
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
126126
.label = initializing type with `rustc_layout_scalar_valid_range` attr
127127
128+
mir_build_initializing_type_with_unsafe_field_requires_unsafe =
129+
initializing type with an unsafe field is unsafe and requires unsafe block
130+
.note = unsafe fields may carry library invariants
131+
.label = initialization of struct with unsafe field
132+
133+
mir_build_initializing_type_with_unsafe_field_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
134+
initializing type with an unsafe field is unsafe and requires unsafe block
135+
.note = unsafe fields may carry library invariants
136+
.label = initialization of struct with unsafe field
137+
128138
mir_build_inline_assembly_requires_unsafe =
129139
use of inline assembly is unsafe and requires unsafe block
130140
.note = inline assembly is entirely unchecked and can cause undefined behavior
@@ -340,6 +350,16 @@ mir_build_unreachable_pattern = unreachable pattern
340350
.unreachable_covered_by_many = multiple earlier patterns match some of the same values
341351
.suggestion = remove the match arm
342352
353+
mir_build_unsafe_field_requires_unsafe =
354+
use of unsafe field is unsafe and requires unsafe block
355+
.note = unsafe fields may carry library invariants
356+
.label = use of unsafe field
357+
358+
mir_build_unsafe_field_requires_unsafe_unsafe_op_in_unsafe_fn_allowed =
359+
use of unsafe field is unsafe and requires unsafe block
360+
.note = unsafe fields may carry library invariants
361+
.label = use of unsafe field
362+
343363
mir_build_unsafe_fn_safe_body = an unsafe function restricts its caller, but its body is safe by default
344364
mir_build_unsafe_not_inherited = items do not inherit unsafety from separate enclosing items
345365
@@ -388,6 +408,11 @@ mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_requires_unsafe =
388408
.note = initializing a layout restricted type's field with a value outside the valid range is undefined behavior
389409
.label = initializing type with `rustc_layout_scalar_valid_range` attr
390410
411+
mir_build_unsafe_op_in_unsafe_fn_initializing_type_with_unsafe_field_requires_unsafe =
412+
initializing type with an unsafe field is unsafe and requires unsafe block
413+
.note = unsafe fields may carry library invariants
414+
.label = initialization of struct with unsafe field
415+
391416
mir_build_unsafe_op_in_unsafe_fn_inline_assembly_requires_unsafe =
392417
use of inline assembly is unsafe and requires unsafe block
393418
.note = inline assembly is entirely unchecked and can cause undefined behavior
@@ -408,6 +433,11 @@ mir_build_unsafe_op_in_unsafe_fn_union_field_requires_unsafe =
408433
.note = the field may not be properly initialized: using uninitialized data will cause undefined behavior
409434
.label = access to union field
410435
436+
mir_build_unsafe_op_in_unsafe_fn_unsafe_field_requires_unsafe =
437+
use of unsafe field is unsafe and requires unsafe block
438+
.note = unsafe fields may carry library invariants
439+
.label = use of unsafe field
440+
411441
mir_build_unsized_pattern = cannot use unsized non-slice type `{$non_sm_ty}` in constant patterns
412442
413443
mir_build_unused_unsafe = unnecessary `unsafe` block

0 commit comments

Comments
 (0)