Skip to content

Restriction lint for constructing a type with a Drop impl from a raw pointer #5954

Open
@sgrif

Description

@sgrif

What it does

This lint would trigger whenever a function is called that returns an owned type from a raw pointer such as CString::from_raw, String::from_raw_parts, Vec::from_raw_parts, or Box::from_raw. I believe the exact conditions that this lint should trigger are:

  • Does not take &self
  • Takes a *const T or *mut T as any of its arguments
  • Returns a type that is !Copy

But I'd love some feedback on that (especially the third bit, is !Copy the right way to express both a type that impls Drop and a type that has meaningful drop glue?

This would be useful in code bases such as Diesel or rubyfmt, where there is a significant amount of FFI, but it is rare that data owned by Rust is getting passed as a raw pointer. In those code bases, constructing an owned type like String instead of &str is almost always wrong. This is a mistake that's very easy to make, especially for newer Rust programmers, and I would love to require an explicit "no I'm actually sure I own this pointer" in the very few cases where that is actually the case.

I am happy to do the work of implementing this if folks are interested in receiving a PR for this.

Categories (optional)

  • Kind: Restruction lint

The recommended code over the original is that the original will introduce undefined behavior.

Drawbacks

As it is a restriction lint, it's unlikely to be useful to many people.

Example

CString::from_raw(ptr)

Could be written as:

CStr::from_ptr(ptr)

This lint would not be able to make a recommendation in 100% of cases. Special cases would be made for the applicable types in std (Vec, Box, CString, String). This lint would still trigger for Arc and Rc, but I'm not sure if it should recommend & instead or just note that constructing it will result in decreasing the ref count and possibly freeing the value.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lintsE-mediumCall for participation: Medium difficulty level problem and requires some initial experience.L-restrictionLint: Belongs in the restriction lint group

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions