rust-lang / rust-lang/rustfmt

Long chain of functions with generic parameter at the end gets badly formatted

Open
#5,356 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

I-poor-formatting P-low
Dominant language
Rust
Stars
7k
Forks
1.1k
Avg merge
2d 13h
Merged PRs (30d)
24

Description

I have code that looks like this after formatting it with Rustfmt: (playground link)

#![allow(dead_code)]

use core::mem;

enum SomeError {
    OutOfMemory(OutOfMemory),
}

pub struct OutOfMemory {
    bytes_requested: usize,
}

impl OutOfMemory {
    fn new(bytes_requested: usize) -> Self {
        Self { bytes_requested }
    }
}

struct SomeType;

fn fail() -> Result<(), SomeError> {
    if true {
        if true {
            if true {
                // this part right here
                return Err(SomeError::OutOfMemory(OutOfMemory::new(mem::size_of::<
                    SomeType,
                >(
                ))));
            }
        }
    }

    Ok(())
}

As you can see, the generic parameter gets put on its own line and the () become disconnected:

                return Err(SomeError::OutOfMemory(OutOfMemory::new(mem::size_of::<
                    SomeType,
                >(
                ))));

In my opinion this would be much more readable if it was formatted like this:

                return Err(SomeError::OutOfMemory(OutOfMemory::new(
                    mem::size_of::<SomeType>(),
                )));

Interestingly, making the line even longer by replacing mem with core::mem, produces exactly this output:

                return Err(SomeError::OutOfMemory(OutOfMemory::new(
                    core::mem::size_of::<SomeType>(),
                )));
Meta
rustfmt --version
rustfmt 1.4.38-nightly (1fede17 2022-05-28)

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

Start with the linked Rust Playground example and reproduce the output using the reported rustfmt 1.4.38-nightly version. Trace the formatting of the chained generic call and compare it with the requested output; the issue is done when the generic parameter and empty argument list remain together in the formatted result.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.