Pre-RFC: Deprecate auto(de)ref in unsafe code

I was just re-reading rustc performs auto-ref when a raw pointer would be enough · Issue #73987 · rust-lang/rust · GitHub, and had an idea: To avoid accidentally calling a &self method when a self: *[const|mut] Self method of the same would have been the better choice, could we deprecate auto-ref and auto-deref in unsafe code (and possibly even remove it in a future edition)?

This would also help with other concerns such as exception safety, which can lead only to logic bugs in safe code, but to critical memory safety bugs in unsafe code. As an example of this, AFAIK std::ptr::addr_of is not magic enough to prevent auto-deref in the inner expression and so field projections like addr_of!((*foo).bar) may actually assert that foo doesn't dangle / points to initialized memory, which is the very thing addr_of! is supposed to prevent.

Of course this could lead to a decent amount of churn so it would have to start off as an allow-by-default lint, but I could see it being very useful for writing some unsafe code, especially when running it through Miri is not an option (e.g. when calling into C libraries or asm, such as for direct syscalls).

2 Likes

This is way to pervasive. Maybe we can warn about specific functions, but there's a lot of unsafe code out there, too much to change.

I think a good place to start would be implementing this as a Clippy lint: New lint: deref coercions · Issue #7104 · rust-lang/rust-clippy · GitHub

5 Likes

Could it be linted only for references created from dereferences of raw pointers?

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.