Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement the unsafe-fields RFC. #132915

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

veluca93
Copy link
Contributor

@veluca93 veluca93 commented Nov 11, 2024

@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue. labels Nov 11, 2024
@rustbot
Copy link
Collaborator

rustbot commented Nov 11, 2024

Some changes occurred in src/tools/rustfmt

cc @rust-lang/rustfmt

@rust-log-analyzer

This comment has been minimized.

@rustbot
Copy link
Collaborator

rustbot commented Nov 11, 2024

Changes to the size of AST and/or HIR nodes.

cc @nnethercote

Copy link
Member

@jswrenn jswrenn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for implementing this! Here's a first round of comments. :-)

compiler/rustc_feature/src/unstable.rs Outdated Show resolved Hide resolved
compiler/rustc_metadata/src/rmeta/encoder.rs Outdated Show resolved Hide resolved
compiler/rustc_mir_build/src/check_unsafety.rs Outdated Show resolved Hide resolved
compiler/rustc_mir_build/src/check_unsafety.rs Outdated Show resolved Hide resolved
@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 11, 2024
@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

@rust-log-analyzer

This comment has been minimized.

compiler/rustc_feature/src/unstable.rs Outdated Show resolved Hide resolved
@veluca93 veluca93 force-pushed the unsafe-fields branch 2 times, most recently from ff9aee3 to db32d80 Compare November 11, 2024 23:33
@jswrenn
Copy link
Member

jswrenn commented Nov 12, 2024

@bors try @rust-timer queue

@rust-timer

This comment has been minimized.

@rustbot rustbot added the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 12, 2024
bors added a commit to rust-lang-ci/rust that referenced this pull request Nov 12, 2024
Draft implementation of unsafe-fields.

RFC: rust-lang/rfcs#3458

Tracking:

- rust-lang#132922

r? jswrenn
@bors
Copy link
Contributor

bors commented Nov 12, 2024

⌛ Trying commit db32d80 with merge ce25ffa...

@bors
Copy link
Contributor

bors commented Nov 12, 2024

☀️ Try build successful - checks-actions
Build commit: ce25ffa (ce25ffa95be3a8577d9d1ff09eafe449df2dcfc3)

@rust-timer

This comment has been minimized.

@rust-timer
Copy link
Collaborator

Finished benchmarking commit (ce25ffa): comparison URL.

Overall result: ❌✅ regressions and improvements - no action needed

Benchmarking this pull request likely means that it is perf-sensitive, so we're automatically marking it as not fit for rolling up. While you can manually mark this PR as fit for rollup, we strongly recommend not doing so since this PR may lead to changes in compiler perf.

@bors rollup=never
@rustbot label: -S-waiting-on-perf -perf-regression

Instruction count

This is the most reliable metric that we have; it was used to determine the overall result at the top of this comment. However, even this metric can sometimes exhibit noise.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
0.0% [0.0%, 0.0%] 1
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
-1.2% [-1.2%, -1.2%] 1
All ❌✅ (primary) - - 0

Max RSS (memory usage)

Results (primary -0.7%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
1.8% [1.8%, 1.8%] 1
Regressions ❌
(secondary)
- - 0
Improvements ✅
(primary)
-3.1% [-3.1%, -3.1%] 1
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) -0.7% [-3.1%, 1.8%] 2

Cycles

Results (secondary 1.7%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
- - 0
Regressions ❌
(secondary)
1.7% [1.7%, 1.7%] 1
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) - - 0

Binary size

Results (primary 0.2%, secondary 0.3%)

This is a less reliable metric that may be of interest but was not used to determine the overall result at the top of this comment.

mean range count
Regressions ❌
(primary)
0.2% [0.0%, 0.5%] 128
Regressions ❌
(secondary)
0.3% [0.0%, 0.5%] 29
Improvements ✅
(primary)
- - 0
Improvements ✅
(secondary)
- - 0
All ❌✅ (primary) 0.2% [0.0%, 0.5%] 128

Bootstrap: 787.726s -> 783.8s (-0.50%)
Artifact size: 335.35 MiB -> 335.31 MiB (-0.01%)

@rustbot rustbot removed the S-waiting-on-perf Status: Waiting on a perf run to be completed. label Nov 12, 2024
@jswrenn
Copy link
Member

jswrenn commented Nov 19, 2024

The UI testing checklist I'd like to see completed before we merge this:

  • if feature(unsafe_fields):
    • the 'incomplete features' warning is emitted
    • unsafe can be applied to the fields of struct-like variant fields of structs, enums and unions
      • the unsafe field's type must be Copy or ManuallyDrop
    • unsafe cannot be applied to tuple-like struct fields
    • unsafe cannot be applied to tuple-like enum fields
  • if not feature(unsafe_fields), even in cfg'd-out code:
    • unsafe cannot be applied to the fields of struct-like struct fields
    • unsafe cannot be applied to the fields of struct-like enum fields
    • unsafe cannot be applied to the fields of struct-like (i.e., all) unions
  • even if not feature(unsafe_fields):
    • initializing, destructuring, referencing, reading, and writing the unsafe fields of a struct/enum/union can only occur in an unsafe context (see these tests as a rough point of reference)
    • initializing, destructuring, referencing, reading, and writing the safe fields of a struct/enum/union (even one that that has other unsafe fields) does not require unsafe

@rustbot
Copy link
Collaborator

rustbot commented Nov 20, 2024

Changes to the size of AST and/or HIR nodes.

cc @nnethercote

@rust-log-analyzer

This comment has been minimized.

@bors
Copy link
Contributor

bors commented Nov 20, 2024

☔ The latest upstream changes (presumably #133212) made this pull request unmergeable. Please resolve the merge conflicts.

@traviscross traviscross added the F-unsafe_fields `#![feature(unsafe_fields)]` label Nov 20, 2024
@rustbot rustbot added S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. and removed S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. labels Nov 21, 2024
@bors
Copy link
Contributor

bors commented Nov 21, 2024

☔ The latest upstream changes (presumably #133280) made this pull request unmergeable. Please resolve the merge conflicts.

Copy link
Member

@jswrenn jswrenn left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is looking pretty good. Be sure to update the commit message, too! It's no longer a draft implementation — it's just an implementation. :-)

tests/ui/feature-gates/feature-gate-unsafe_fields.rs Outdated Show resolved Hide resolved
tests/ui/unsafe-fields.rs Show resolved Hide resolved
tests/ui/unsafe-fields.rs Show resolved Hide resolved
safe_field: u32,
}

impl WithUnsafeField {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a test tracking the behavior of this:

&raw const self.unsafe_field

I think (but am not completely certain) it's safe, but we should probably require unsafe in the initial implementation.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I would prefer this to be unsafe -- of course, to do something with the result of this that could possibly cause problems requires some other form of unsafe somewhere else (I think...), but making this unsafe is IMO nice because it improves locality-of-safety:

let ptr = &raw const self.unsafe_field;

// lots of code

unsafe { do_something_with_ptr }

I think it'd be nice to have some sign somewhere that ptr actually comes from an unsafe field.

Copy link
Member

@compiler-errors compiler-errors Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think (but am not completely certain) it's safe

It's not safe. All field accesses are "inbounds", so they need to point to valid memory to even take the offset.

See rust-lang/opsem-team#10

@rustbot rustbot added S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. and removed S-waiting-on-review Status: Awaiting review from the assignee but also interested parties. labels Nov 21, 2024
@rust-log-analyzer

This comment has been minimized.

Co-Authored-By: Jacob Pratt <jacob@jhpratt.dev>
@veluca93 veluca93 changed the title Draft implementation of unsafe-fields. Implement the unsafe-fields RFC. Nov 21, 2024
Copy link
Member

@compiler-errors compiler-errors left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Generally looks okay. I've got some minor comments about style and code deduplication.

fn parse_unsafe_field(&mut self) -> Safety {
// not using parse_safety as that also accepts `safe`.
if self.eat_keyword(kw::Unsafe) {
let span = self.prev_token.uninterpolated_span();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you gating the uninterpolated span? Everywhere else in the parser seems to gate on prev_token.span.

if let ty::Adt(adt_def, ..) = pat.ty.kind() {
for pat in subpatterns {
let field = &pat.field;
if adt_def.variants().iter().next().unwrap().fields[*field].safety
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think you should use non_enum_variant here:

Suggested change
if adt_def.variants().iter().next().unwrap().fields[*field].safety
if adt_def.non_enum_variant().fields[*field].safety

I don't think(?) we use PatKind::Leaf for enums ever.

if let ty::Adt(adt_def, ..) = pat.ty.kind() {
for pat in subpatterns {
let field = &pat.field;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why are you taking a ref of a FieldIdx, just to deref it below?

Copy link
Member

@compiler-errors compiler-errors Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Just inline this into the .fields[&pat.field] below.

@@ -1599,6 +1599,10 @@ impl<'a, 'tcx> EncodeContext<'a, 'tcx> {
f.did.index
}));

for field in &variant.fields {
self.tables.safety.set_some(field.did.index, field.safety);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

record!(self.tables.safety[field.did] <- field.safety);

Comment on lines +159 to +160
for variant in def.variants() {
for field in &variant.fields {
Copy link
Member

@compiler-errors compiler-errors Nov 21, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This can be a single for loop with def.all_fields().

continue;
};

if !allowed_union_or_unsafe_field(field_ty, tcx, typing_env) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

tiny nit: always pass tcx as the first field

let (field_span, ty_span) = match tcx.hir().get_if_local(field.did) {
// We are currently checking the type this field came from, so it must be local.
Some(Node::Field(field)) => (field.span, field.ty.span),
_ => unreachable!("mir field has to correspond to hir field"),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This comment doesn't really make sense. This isn't a "MIR" field, it's just the middle typing layer.

I think this can be simplified to field.did.expect_local(), though, no need for the match.

} else if field_ty.needs_drop(tcx, typing_env) {
// This should never happen. But we can get here e.g. in case of name resolution errors.
tcx.dcx()
.span_delayed_bug(span, "we should never accept maybe-dropping union fields");
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

union -> unsafe?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also, this could perhaps be moved into allowed_union_or_unsafe_field to deduplicate this logic further.

@@ -1464,6 +1506,7 @@ fn check_enum(tcx: TyCtxt<'_>, def_id: LocalDefId) {

detect_discriminant_duplicate(tcx, def);
check_transparent(tcx, def);
check_unsafe_fields(tcx, tcx.def_span(def_id), def_id);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

no need to pass the def span of the def id we're already passing in.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
F-unsafe_fields `#![feature(unsafe_fields)]` S-waiting-on-author Status: This is awaiting some action (such as code changes or more information) from the author. T-compiler Relevant to the compiler team, which will review and decide on the PR/issue.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

8 participants