udoprog / genco

A whitespace-aware quasiquoter for beautiful code generation.
Apache License 2.0
181 stars 11 forks source link

Add support for variable declarations in templates #55

Closed swallez closed 3 months ago

swallez commented 3 months ago

Adds support for variable declarations in quote! templates.

This is useful within loops to compute values from iterator items. Example:

let names = ["A.B", "C.D"];

let tokens: Tokens<()> = quote! {
    $(for name in names =>
        $(let (first, second) = name.split_once('.').unwrap())
        $first and $second.
    )
};
udoprog commented 3 months ago

Hi, thanks for the contribution!

This could definitely be useful, all though for your example I'd probably opt to do this:

let names = ["A.B", "C.D"];

let tokens: Tokens<()> = quote! {
    $(for (first, second) in names.iter().flat_map(|s| s.split_once('.')) =>
        $first and $second.
    )
};

I don't particularly mind merging it though since it seems like a natural extension, but I'm not sure if there are any clear patterns that should be encouraged.

swallez commented 3 months ago

Thanks for your review! Regarding your comment on the example, it is a bit contrived to be short, and you're right that an additional map could do it. It can lead to long verbose for expressions though. And it starts to be cumbersome if you want to also keep the original item and have to keep it in a tuple along with the derived value.

The let statement increases readability IMHO, even more in long templates where the let that creates a derived value can be located near it's actual use.

udoprog commented 3 months ago

Impl looks good. Nicely done!

swallez commented 3 months ago

Impl looks good. Nicely done!

Thanks! And thank you for this great library. I evaluated several ways to generate source code files more easily than with the classic quote (this isn't for procmacros) and genco really stood out.

udoprog commented 3 months ago

This is now out in 0.17.9.