Skip to content

New lint: deref coercions #7104

Open
@Aaron1011

Description

@Aaron1011

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

Metadata

Metadata

Assignees

Labels

A-lintArea: New lintsL-restrictionLint: Belongs in the restriction lint groupgood first issueThese issues are a good way to get started with Clippy

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions