rust-lang / rustfmt

Format Rust code
https://rust-lang.github.io/rustfmt/
Apache License 2.0
5.97k stars 879 forks source link

Long statements continues on its own line #3626

Open tesuji opened 5 years ago

tesuji commented 5 years ago

Playground

I tried to format this code:

fn main() {
    let visual_studio_path = {
        let vswhere_stdout = String::from_utf8(vswhere_output.stdout)
    .expect("vswhere output is not valid UTF-8");
        String::from(vswhere_stdout.trim())
    };
}

What I expect:

fn main() {
    let visual_studio_path = {
        let vswhere_stdout = String::from_utf8(vswhere_output.stdout)
            .expect("vswhere output is not valid UTF-8");
        String::from(vswhere_stdout.trim())
    };
}

What I got:

fn main() {
    let visual_studio_path = {
        let vswhere_stdout =
            String::from_utf8(vswhere_output.stdout).expect("vswhere output is not valid UTF-8");
        String::from(vswhere_stdout.trim())
    };
}
NyxCode commented 4 years ago

I agree. Is there a way to configure this?

calebcartwright commented 4 years ago

I believe the RHS (String::from_utf8(vswhere_output.stdout).expect("vswhere output is not valid UTF-8");) is being formatted as a chain, and rustfmt tries to keep chains on one line wherever possible.

However, there's arguably either a need to clarify chain handling within the style guide, and/or this is a bug. The relevant section on chains from the style guide has two snippets that seem particularly relevant:

A chain is a sequence of field accesses and/or method calls

and

Prefer formatting on one line if possible, and the chain is small

There's only one method call, so I suppose it's worth asking if that single method call qualifies as a "sequence". If it does, however, then this chain wouldn't qualify as "small" because the formatted length of the chain (~80) exceeds the threshold for a small chain as defined by chain_width/use_small_heuristics (60), and the chain should be formatted vertically.

If rustfmt will always try to keep a chain on one line (regardless of whether it qualifies as "small" /exceeds chain_width), or will do so with chains that have only one child element, then IMHO that should be codified within the style guide.

If that's indeed the preferred default behavior, then it also begs the question of whether there should be a config option to provide an escape hatch for folks that would rather have the chain formatted vertically to keep the chain parent on the same line as the LHS.

ytmimi commented 2 years ago

Related to https://github.com/rust-lang/rustfmt/issues/3514#issuecomment-720175287, and pretty much the exact opposite request mad in #3514