rustfmt
rustfmt copied to clipboard
Sort items in a file to make it readable top to bottom
I love that in Rust I can declare items in a file wherever I want.
On the other hand, I also like to read source files, typically top to bottom.
It would be great if rustfmt
could have an opt-in option (e.g. via cargo fmt
) that would sort the items in a file, so that ideally an item is declared / implemented before it is used in the implementation of another item (cargo fmt --sort-items
).
A perfect output might not be always possible, but something "good enough" would already make many of my files much more "readable" top to bottom.
Also, if this is desired (I'd like something like it), it should probably be planned with configuration in mind, for example, in some cases, a user might want to interleave tests with items (e.g. the test of an item follow or preceed the item in the source file), while in other cases the user might want to put all the tests at the bottom of the source file, sorted top-to-bottom in the same order as the items. Relating a test to an item would need some heuristic, like the test should contain the item in its name or something.
Anyways, I just ended up writing a "huge" file (>2kLOC) and had to skim a lot through some "huge" files in the std
library, and would have appreciated something like this.
Maybe sort items by usage?
fn foo() {
bar();
baz();
}
fn baz() {
println!("World!");
}
fn bar() {
gah();
}
fn gah() {
println!("Hello");
}
After sort:
fn gah() {
println!("Hello");
}
fn bar() {
gah();
}
fn baz() {
println!("World!");
}
fn foo() {
bar();
baz();
}
or inverse sorting:
fn foo() {
bar();
baz();
}
fn bar() {
gah();
}
fn gah() {
println!("Hello");
}
fn baz() {
println!("World!");
}
I'd really the ability to sort definitions of structs, unions and enums before their impls (eg to clean up the awful mess that bindgen produces). I also prefer a style of having impls of traits before impls of the struct, but I can live without that.
This would be particularly useful for generated code - we check in some prost generated code into our repo, and regenerating can sometimes have nondeterministic results with ordering of items in the files (even though they're semantically the exact same). Being able to sort the file somehow would be awesome 👍