dampen_core/codegen/
update.rs

1//! Update function generation
2
3use crate::HandlerSignature;
4use proc_macro2::TokenStream;
5use quote::{format_ident, quote};
6
7/// Convert snake_case to UpperCamelCase
8fn to_upper_camel_case(s: &str) -> String {
9    let mut result = String::new();
10    let mut capitalize_next = true;
11    for c in s.chars() {
12        if c == '_' {
13            capitalize_next = true;
14        } else if capitalize_next {
15            result.push(c.to_ascii_uppercase());
16            capitalize_next = false;
17        } else {
18            result.push(c);
19        }
20    }
21    result
22}
23
24/// Generate the update match arms for use in a standalone function
25pub fn generate_update_match_arms(
26    handlers: &[HandlerSignature],
27    message_name: &str,
28) -> Result<TokenStream, super::CodegenError> {
29    let message_ident = format_ident!("{}", message_name);
30
31    let match_arms: Vec<TokenStream> = handlers
32        .iter()
33        .map(|handler| {
34            let handler_name = format_ident!("{}", handler.name);
35            let variant_name = to_upper_camel_case(&handler.name);
36            let variant_ident = syn::Ident::new(&variant_name, proc_macro2::Span::call_site());
37
38            if let Some(_param_type) = &handler.param_type {
39                quote! {
40                    #message_ident::#variant_ident(value) => {
41                        ui::window::#handler_name(model, value);
42                        iced::Task::none()
43                    }
44                }
45            } else if handler.returns_command {
46                quote! {
47                    #message_ident::#variant_ident => {
48                        ui::window::#handler_name(model)
49                    }
50                }
51            } else {
52                quote! {
53                    #message_ident::#variant_ident => {
54                        ui::window::#handler_name(model);
55                        iced::Task::none()
56                    }
57                }
58            }
59        })
60        .collect();
61
62    Ok(quote! {
63        match message {
64            #(#match_arms)*
65        }
66    })
67}