rust-lang/rust-clippy

New lint: deref coercions

Open

#7 104 ouverte le 17 avr. 2021

Voir sur GitHub
 (6 commentaires) (0 réactions) (1 assigné)Rust (1 391 forks)batch import
A-lintL-restrictiongood first issue

Métriques du dépôt

Stars
 (10 406 stars)
Métriques de merge PR
 (Merge moyen 19j 22h) (113 PRs mergées en 30 j)

Description

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();
}

Guide contributeur