rustfmt icon indicating copy to clipboard operation
rustfmt copied to clipboard

Allow manually-specifying which macros should be formatted and how

Open gnzlbg opened this issue 6 years ago • 6 comments

The libc crate has some macros, called s!, f!, etc. which take a series of items:

f! {
    fn foo();
    fn bar();
    // ...
}

I know that formatting macros is very tricky, and that we probably cannot do that by default.

Instead, would it be possible to specify, e.g., in the rustfmt.toml, a list of macros for which rustfmt should try to format the contents as if the contents were a sequence of items ?

E.g. for the case above, rustfmt could format the f! { ... } the contents of ... as if they were items, adding 4 space indentation inside the block.

I think approaches to macros in which users opt-into formatting them, and somehow conveying what the content of the macro is, might be a more viable way forward with respect to macro formatting than trying to do things automatically.

I don't know how to call this, but I could add the following to libc's rustfmt.toml:

format-macro-content-as-items = ["f", "s"]

I think I could use this in other crates that also make heavy use of macros, like packed-simd.

gnzlbg avatar Jul 27 '19 12:07 gnzlbg

For many macros, specifying the separator of a list of arguments would be necessary and sufficient. "You're allowed to modify whitespace immediately after this pattern."

Of course this might break in a few special cases, but if it's opt-in that's OK - use it in the other cases.

cphoenix-google avatar Sep 21 '19 01:09 cphoenix-google

Also, rather than specifying it in the .toml, how about a #[rustfmt::] block on the macros you want to format? That would give finer-grained control, more closely linked to the source you want to affect (you don't have to export your .toml to let others format your macro invocations).

// For keyword-args like my_macro!(foo: 5, bar: 6, baz: 7) #[rustfmt::macro_args_separator(",")]

// For the example above with a list of functions #[rustfmt::macro_args_separator(";")]

cphoenix-google avatar Sep 21 '19 01:09 cphoenix-google

Is there any progress on this? Is there anyway to format macros that just receive regular rust code?

Zizico2 avatar Jan 02 '21 01:01 Zizico2

This would also be useful in Tokio.

Darksonn avatar Jan 20 '21 22:01 Darksonn

This would be useful in Maud as well (though its syntax might be too complex for a config-driven solution...)

lambda-fairy avatar Mar 13 '21 09:03 lambda-fairy

I have opened a discussion thread in the Rust Internals Forum related to this issue. If there is something constructive you could add to the discussion (criticism, possible solutions, concerns, use cases), please head through the link below. https://internals.rust-lang.org/t/discussion-adding-grammar-information-to-procedural-macros-for-proper-custom-syntax-support-in-the-toolchain/21496

chipnertkj avatar Sep 06 '24 13:09 chipnertkj