rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

Implement remove_nested_blocks option

Open karolzwolak opened this issue 8 months ago • 0 comments
trafficstars

Implements new feature that removes nested blocks #5616. The feature is similar to remove_nested_parens. Blocks with any sort of comments or attributes, unsafe and const blocks will not be removed. This however will not remove all nested blocks, instead it will leave the innermost block (similar to remove_nested_parens). That behavior differs from suggested in the issue, and I'm not sure which one is better.

I'm not fully satisfied with my implementation, so any suggestions are appreciated. I also was not sure what do do if nested blocks are of different kind (nested const and/or unsafe blocks), so I decided to only remove 'naked' blocks, and just never remove const and unsafe blocks. There is some merit to removing unsafe or const blocks when only blocks of one kind are nested, but for the sake of consistency I decided to not do that. An example of such problematic situation:

// rustfmt-remove_nested_blocks: true
fn foo() {}
fn one_kind() {
    { // <- this block would be removed if not for this comment
        const { const {} }
    }
}
fn mixed() {
    unsafe {
        unsafe {
            { // <- this block would be removed if not for this comment
                const {
                    const {
                        { // this block will not be removed regardless of the comment
                            foo();
                        }
                    }
                }
            }
        }
    }
}

As I said, for now both mixed, and one_kind functions would only remove the blocks annotated by comments. I'm open for suggestions regarding the behavior, since the feature in the original issue was very loosely defined (also blocks are more tricky than parentheses)

karolzwolak avatar Feb 26 '25 22:02 karolzwolak