rust-lang / rust-lang/rust-clippy

New lint: Oddly nested item definitions

Open
#6,906 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-lint E-medium
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

What it does

Rust's syntax is quite flexible:

  • Items can written in statement position (e.g. fn bar() { struct Foo; })
  • Arbitrary statements can occur inside a block expression (e.g. let a = { struct Foo; };
  • The array type [T; size] supports arbitrary (const-evaluatable) expressions for size.

By combining these features, we can write code like this:

pub struct Foo<T>(T);

impl Foo<[u8; {
    pub struct Inner {
        field: [bool; {
            struct AnotherStruct;
            0
        }]
    };
    0
}]> {}

However, this kind of code is an unreadable mess. When combined with #[cfg], #[cfg_attr] and #[derive], it can become extremely difficult to tell what's going on. In addition, it currently breaks GitHub's Rust syntax highlighting.

Clippy should lint against items that occur in an 'unusual position' (for example, inside blocks used in expression position).

Categories (optional)
  • Kind: clippy::style (potentially also clippy::complexity, but there is not necessarily a 'simple' equivalent to code written in this way).

What is the advantage of the recommended code over the original code

Code written without this kind of nesting is much easier to understand, especially for people coming from languages where this kind of nesting is not allowed.

Drawbacks

Because of the complexity of this kind of deeply nested code (especially w.r.t name resolution and macro expansion), we cannot suggest equivalent code in the general case. This lint would be limited to alerting developers about the presence of extremely convoluted code in their project.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

No source file, test, or entry point is named. Start by reviewing the Rust examples in the issue and the existing Clippy lint conventions, then define which unusually nested item positions are in scope and how the lint should handle cfg attributes, derives, macros, and cases where no general replacement can be suggested.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.