rust-lang/rust-clippy

New lint: deref coercions

Open

#7104 aperta il 17 apr 2021

Vedi su GitHub
 (6 commenti) (0 reazioni) (1 assegnatario)Rust (1391 fork)batch import
A-lintL-restrictiongood first issue

Metriche repository

Star
 (10.406 star)
Metriche merge PR
 (Merge medio 19g 22h) (113 PR mergiate in 30 g)

Descrizione

What it does

Lints on any use of deref coercions - for example, accessing a field or method through a Deref impl

Categories (optional)

  • Kind: Restriction lint

What is the advantage of the recommended code over the original code

Normally, deref coercions are a very useful part of rust, making smart points like Box, Rc, Ref, and RefMut much easier to use. However, this can be undesirable when writing unsafe code, since a non-trivial function call could be completely hidden from view. For example:

  • Unsafe code can temporarily put data structures in an unusual state, which will lead to undefined behavior if dropped (e.g. Vec::set_len). A deref coercion might cause a panic at an unexpected point (due to a panicking user-supplied Deref impl), leading to undefined behavior.
  • When mixing raw pointers and references, it's important to pay attention to the provenance of pointers. A deref coercion can hide the creation of an &self reference behind what looks like a normal field access, leading to a very subtle form of undefined behavior.

Drawbacks

This would be a fairly niche lint - unless you're writing unsafe code, there's little need to use it.

Example

fn main() {
    let a = Box::new(true);
    let b: &bool = &a;
}

Could be written as:

use std::ops::Deref;
fn main() {
    let a = Box::new(true);
    let b: &bool = (&a).deref();
}

Guida contributor