Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for variable declarations in templates #55

Merged
merged 3 commits into from
May 18, 2024

Conversation

swallez
Copy link
Contributor

@swallez swallez commented May 18, 2024

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
Copy link
Owner

udoprog commented May 18, 2024

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
Copy link
Contributor Author

swallez commented May 18, 2024

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
Copy link
Owner

udoprog commented May 18, 2024

Impl looks good. Nicely done!

@swallez
Copy link
Contributor Author

swallez commented May 18, 2024

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 udoprog merged commit db32718 into udoprog:main May 18, 2024
5 checks passed
@swallez swallez deleted the add-variables branch May 18, 2024 15:17
@udoprog
Copy link
Owner

udoprog commented May 18, 2024

This is now out in 0.17.9.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants