Skip to content

Detect Enum Objects with empty attribute body using {} #12007

@jetlime

Description

@jetlime

What it does

The proposed lint feature aims to improve code readability and consistency by discouraging the use of empty attribute objects {} succeeding structures without attributes. In Rust, empty attribute objects are often used to represent variants of an enum that carry no additional information. However, this usage can be misleading and may result in less expressive and clear code.

This lint feature shall check for the presence of empty attribute objects {} immediately following enum variants without associated data. If such a pattern is detected, the lint will emit a warning. This warning encourages developers to reconsider the necessity of the empty attribute object and suggests using the enum variant directly without the unnecessary attribute object.

Advantage

  • Prevent Code Blow, simplify code.

Drawbacks

No response

Example

pub enum Decoder {
    Absent {},
    Symbol(u8)
}


#[derive(Debug, thiserror::Error)]
pub enum CustomError {
    #[error("This is a custom error without attributes.")]
    CustomError { },
}

type Result<T, E = CustomError> = std::result::Result<T, E>;

impl Decoder {
    /// # Errors
    /// 
    /// May return an error..
    pub fn decode(&mut self, input: u64) -> Result<u8> {
            if input > 1 { return Err(CustomError::CustomError { })};

            match self {
                Decoder::Symbol(symbol) => {
                    Ok(*symbol)
                }
                Decoder::Absent{} => {
                    Ok(b'i')
                }
            }
    }
}

Could be written as:

pub enum Decoder {
    Absent,
    Symbol(u8)
}

#[derive(Debug, thiserror::Error)]
pub enum CustomError {
    #[error("This is a custom error without attributes.")]
    CustomError,
}

type Result<T, E = CustomError> = std::result::Result<T, E>;

impl Decoder {
    /// # Errors
    /// 
    /// May return an error..
    pub fn decode(&mut self, input: u64) -> Result<u8> {
            if input > 1 { return Err(CustomError::CustomError)};

            match self {
                Decoder::Symbol(symbol) => {
                    Ok(*symbol)
                }
                Decoder::Absent => {
                    Ok(b'i')
                }
            }
    }
}

In both cases, the nursery and the pedantic mode of clippy do not output any warnings nor errors. To prevent code blow, structures without attributes shall not be allowed to be succeeded by an empty attribute object, {}. The example shall result in a warning, while the second one should not.

### Tasks

Metadata

Metadata

Assignees

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