Skip to content

[lint] Impl Ordering within file #16189

@feliblo

Description

@feliblo

What it does

Does this exist already? I'd like it for large files to have standard ordering?

Impls following standard orders e.g. (all alphabetical?)

  1. Inherent
  2. Standard lib
  3. External crate
  4. Custom

Advantage

  • Large files follow standard patterns

Drawbacks

Maybe as an opt in with config, because:

  1. Maybe you dont want this?
  2. Maybe bad for multiple structs in a file?
  3. Impls in other files
  4. It's already somewhere and I'm blind?
  5. Most important functional impls manually still need to be at the top?

Example

struct MyType {
    value: i32,
}

// 1. External crate trait appears first
impl serde::Serialize for MyType { /* ... */ }

// 2. Custom trait appears before standard library traits
impl MyTrait for MyType { /* ... */ }

// 3. Standard library traits are out of alphabetical order
impl Debug for MyType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MyType({})", self.value)
    }
}

impl Clone for MyType {
    fn clone(&self) -> Self {
        MyType { value: self.value }
    }
}

// 4. Inherent impl appears last
impl MyType {
    fn new(value: i32) -> Self {
        MyType { value }
    }
}

Could be written as:

struct MyType {
    value: i32,
}

// 1. Inherent impl
impl MyType {
    fn new(value: i32) -> Self {
        MyType { value }
    }
}

// 2. Standard library traits (alphabetical)
impl Clone for MyType {
    fn clone(&self) -> Self {
        MyType { value: self.value }
    }
}

impl Debug for MyType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "MyType({})", self.value)
    }
}

// 3. External crate traits (alphabetical)
impl serde::Serialize for MyType { /* ... */ }

// 4. Custom traits (alphabetical)
impl MyTrait for MyType { /* ... */ }

Comparison with existing lints

No response

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions