Feature request: proc_macro with content as string

I wonder if Rust could eventually allow something like #[proc_macro_string] or #[proc_macro_block]. White space, en dash and other things makes things harder than needed when implementing a macro, at the moment. The idea is to take take the block as string and pass it to the macro.

Example:


#[proc_macro_block]

pub fn html(input: &str) -> TokenStream {

// process input block

}

Usage:


let content = html! {

<h1>The string to process</h1>

};

I can work on this. Would the change be accepted?

I don't think such a change would be accepted. That would make it impossible for rustfmt to do any formatting inside of macro bodies. Also how would we delimit the body if the body is allowed to contain arbitrary data, including unbalanced { and }? The Rust syntax becoming whitespace sensitive would also be a major change and surprising for many people. You are probably better off just accepting a string literal inside your macro like so:

let content = html! {r#"

<h1>The string to process</h1>

"#};
4 Likes

Thanks.

Formatting can still be done on some macro bodies but not on the ones that care about white space.

Balanced { could still be a requirement.

Rustfmt has no way to know if a macro invocation is for a macro that cares about whitespace. Knowing that requires doing name resolution and macro expansion, both of which are impossible for rustfmt as it works on individual files and doesn't have access to crate metadata for dependencies.

2 Likes

I think I'd much rather have a my_macro!"foobar" syntax at that point, which could just desugar to a proc macro which has a single string literal in its token stream. Although at that point I'd think why not allow that syntax for other literals too, like my_macro!32 which is then hard to argue to be distinct from custom integer literals like 32my_macro.

On the implementation side passing which token the macro was called with (my_macro!(), my_macro![], my_macro!{}) using a macro metadata as a second parameter (like is being discussed with const derives right now) might be interesting as a more general addition.

1 Like