rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

rustfmt does not format deeply nested functional code

Open evlogiy opened this issue 1 year ago • 1 comments

rustfmt does not apply any formatting to the contents of the following Rust function (which compiles and works as expected):

fn determinant(matrix: &[Vec<i64>]) -> i64 {
    match matrix.len(){1=>matrix[0][0],2=>matrix[0][0]*matrix[1][1]-matrix[0][1]*matrix[1][0],_=>matrix[0].iter().enumerate().map(|(column,e)|if column%2==0{1}else{-1}*e*determinant(&matrix.iter().skip(1).map(|row|row.iter().enumerate().filter(|(i,_)|*i !=column).map(|(_,&e)|e).collect()).collect::<Vec<Vec<i64>>>())).sum()}
}

I formatted my code as a single line after facing some issues with the formatter. I thought that it might help me see where exactly the problem is. However, when running rustfmt, the only changes it makes are around the function declaration and {}. The internals of the function are left entirely untouched.

Expected behavior: rustfmt should format the function, introducing appropriate indentation and line breaks for readability.

The version currently used in Rust Playground: 1.8.0-beta (2025-02-01 0277061b9a)

Permalink to the playground with unedited one-liner.

Hope this helps.

evlogiy avatar Feb 03 '25 02:02 evlogiy

The last match arm is the issue. It's way too long, and rustfmt can't format the expression within the max width and as a result formatting the match expression fails.

fn determinant(matrix: &[Vec<i64>]) -> i64 {
    match matrix.len() {
        1 => matrix[0][0],
        2 => matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0],
        _ => matrix[0].iter().enumerate().map(|(column, e)| if column % 2 == 0 { 1 } else { -1 } * e * determinant(&matrix.iter().skip(1).map(|row| row.iter().enumerate().filter(|(i, _)| *i != column).map(|(_, &e)| e).collect()).collect::<Vec<Vec<i64>>>())).sum(),
    }
}

ytmimi avatar Feb 07 '25 18:02 ytmimi