rust-lang / rustfmt

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

Wrong formatting #6355

Closed pepa65 closed 1 month ago

pepa65 commented 1 month ago

On this file, the second .expect is indented too far to the left:

use std::fs::File;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let arg = args
        .get(1)
        .unwrap_or_else(|| {
            println!("OK...");
            panic!("No argument")
        })
        .expect("File not readable");

    let file = File::open(args.get(0).unwrap_or_else(|| {
        println!("Strange...");
        panic!("No command!")
    }))
    .expect("File not readable");

    println!("{:?}", file);
}
ytmimi commented 1 month ago

@pepa65 can you elaborate, I don't see anything wrong with the formatting. Are you expecting something like this:

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let arg = args
        .get(1)
        .unwrap_or_else(|| {
            println!("OK...");
            panic!("No argument")
        })
        .expect("File not readable");

    let file = File::open(args.get(0).unwrap_or_else(|| {
        println!("Strange...");
        panic!("No command!")
    }))
      .expect("File not readable");

    println!("{:?}", file);
}
pepa65 commented 1 month ago

Almost, but then a full 8 space indent on the second .expect:

use std::fs::File;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    let arg = args
        .get(1)
        .unwrap_or_else(|| {
            println!("OK...");
            panic!("No argument")
        })
        .expect("File not readable");

    let file = File::open(args.get(0).unwrap_or_else(|| {
        println!("Strange...");
        panic!("No command!")
    }))
        .expect("File not readable");

    println!("{:?}", file);
}

The let statements that have the .expect on their values (arg in the first case, File::open(args.get(0).unwrap_or_else(|| {println!("Strange..."); panic!("No command!")})) in the second case) should have the .expect indented to the same position. But rustfmt puts the last .expect too far to the left (see my initial report).

ytmimi commented 1 month ago
    let file = File::open(args.get(0).unwrap_or_else(|| {
        println!("Strange...");
        panic!("No command!")
    }))
        .expect("File not readable");

This formatting is not correct, and rustfmt does exactly what it does to prevent the .expect("File not readable"); from dangling on its own line.

pepa65 commented 1 month ago

It is not so much about dangling, as it is about consistency in indentation. What if there was another .option, would that also then be straight under the .expect? How does that compare with the let arg statement, where all the .options are indented inwards? They don't get 4 spaces, that would not make sense.