1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
use convert_case::{Case, Casing};
use proc_macro2::{Literal, TokenStream};
use syn::Ident;

use crate::{bundle::MessageBundle, message::Message, Error};
use quote::{format_ident, quote};

use super::{common, CodeGenerator};

pub struct MessageBundleCodeGenerator {
    default_language: String,
}

impl MessageBundleCodeGenerator {
    pub fn new(default_language: &str) -> Self {
        Self {
            default_language: default_language.to_string(),
        }
    }
}

impl CodeGenerator for MessageBundleCodeGenerator {
    fn generate(&self, bundle: &MessageBundle) -> Result<TokenStream, Error> {
        let module_name = bundle.name_ident();
        let struct_name = format_ident!("{}Bundle", bundle.name().to_case(Case::UpperCamel));
        let supported_languages = bundle.language_literals();
        let language_bundles = common::language_bundle_definitions(bundle);
        let language_bundle_lookup_fn =
            common::language_bundle_lookup_function_definition(&self.default_language, bundle)?;
        let message_format_fn = format_ident!("internal_message_format");
        let format_message_fn = format_message_function_definition(&message_format_fn);
        let format_message_functions =
            message_functions_definitions(&self.default_language, bundle, &message_format_fn)?;

        let mut module = quote! {
            #[allow(dead_code)]
            pub mod #module_name {
                #[allow(unused_imports)]
                use fluent_static::fluent_bundle::{FluentBundle, FluentResource, FluentValue, FluentArgs, FluentError};
                use fluent_static::once_cell::sync::Lazy;
                use fluent_static::{LanguageSpec, Message};

                static SUPPORTED_LANGUAGES: &[&str] = &[#(#supported_languages),*];
                #(#language_bundles)*
                #language_bundle_lookup_fn
                #format_message_fn

                #[derive(Clone)]
                pub struct #struct_name {
                    lang: LanguageSpec,
                    bundle: &'static FluentBundle<FluentResource>,
                }

                impl Into<LanguageSpec> for #struct_name {
                    fn into(self) -> LanguageSpec {
                        self.lang
                    }
                }

                impl From<LanguageSpec> for #struct_name {
                    fn from(value: LanguageSpec) -> Self {
                        Self {
                            lang: value.clone(),
                            bundle: get_bundle(value.as_ref())
                         }
                    }
                }

                impl AsRef<str> for #struct_name {
                    fn as_ref(&self) -> &str {
                        self.lang.as_ref()
                    }
                }

                impl #struct_name {
                    pub fn all_languages() -> &'static [&'static str] {
                        SUPPORTED_LANGUAGES
                    }

                    pub fn current_language(&self) -> &LanguageSpec {
                        &self.lang
                    }

                    #(#format_message_functions)*
                }


            }
        };

        let mut parent_path = bundle.path().parent();
        while let Some(parent) = parent_path {
            if let Some(dir_name) = parent.file_name() {
                let name = dir_name
                    .to_str()
                    .ok_or_else(|| Error::InvalidPath(bundle.path().to_path_buf()))?;
                let parent_module_name = format_ident!("{}", name.to_case(Case::Snake));
                module = quote! {
                    pub mod #parent_module_name {
                        #module
                    }
                }
            }
            parent_path = parent.parent();
        }

        Ok(module)
    }
}

pub fn format_message_function_definition(fn_name: &Ident) -> TokenStream {
    quote! {
        fn #fn_name(bundle: &'static FluentBundle<FluentResource>, message_id: &str, args: Option<&FluentArgs>) -> Result<Message<'static>, FluentError> {
            let msg = bundle.get_message(message_id).expect("Message not found");
            let mut errors = vec![];
            let result = Message::new(bundle.format_pattern(&msg.value().unwrap(), args, &mut errors));
            if errors.is_empty() {
                Ok(result)
            } else {
                Err(errors.into_iter().next().unwrap())
            }
        }
    }
}

fn message_function_definition(msg: &Message, delegate_fn: &Ident) -> TokenStream {
    let function_ident = msg.function_ident();
    let message_name_literal = msg.message_name_literal();
    let msg_total_vars = msg.vars().len();
    if msg_total_vars == 0 {
        quote! {
            pub fn #function_ident(&self) -> Message<'static> {
                #delegate_fn(self.bundle, #message_name_literal, None)
                    .expect("Not fallible without variables; qed")
            }
        }
    } else {
        let (function_args, fluent_args): (Vec<Ident>, Vec<TokenStream>) = msg
            .vars()
            .into_iter()
            .map(|var| {
                let name = var.literal();
                let ident = var.ident();
                (
                    ident.clone(),
                    quote! {
                        args.set(#name, #ident);
                    },
                )
            })
            .unzip();
        let capacity = Literal::usize_unsuffixed(msg_total_vars);
        quote! {
            pub fn #function_ident<'a>(&self, #(#function_args: impl Into<FluentValue<'a>>),*) -> Result<Message<'static>, FluentError> {
                let mut args = FluentArgs::with_capacity(#capacity);
                #(#fluent_args)*
                #delegate_fn(self.bundle, #message_name_literal, Some(&args))
            }
        }
    }
}

fn message_functions_definitions(
    default_language: &str,
    bundle: &MessageBundle,
    format_message_name: &Ident,
) -> Result<Vec<TokenStream>, Error> {
    let language_bundle = bundle
        .get_language_bundle(default_language)
        .ok_or_else(|| Error::FallbackLanguageNotFound(default_language.to_string()))?;

    Ok(language_bundle
        .messages()
        .into_iter()
        .map(|msg| message_function_definition(msg, format_message_name))
        .collect())
}

#[cfg(test)]
mod test {
    use quote::quote;

    use crate::{bundle::MessageBundle, codegen::CodeGenerator};

    #[test]
    fn codegen() {
        let message_bundle = MessageBundle::create(
            "messages",
            "test/messages.ftl",
            vec![
                (
                    "en".to_string(),
                    "test=Test message\ntest-args1=Hello { $name }".to_string(),
                ),
                (
                    "en-UK".to_string(),
                    "test=UK message\ntest-args1=Greetings { $name }".to_string(),
                ),
            ],
        )
        .unwrap();

        let actual = super::MessageBundleCodeGenerator::new("en")
            .generate(&message_bundle)
            .unwrap();

        let expected = quote! {
            pub mod test {
                #[allow(dead_code)]
                pub mod messages {
                    #[allow(unused_imports)]
                    use fluent_static::fluent_bundle::{FluentBundle, FluentResource, FluentValue, FluentArgs, FluentError};
                    use fluent_static::once_cell::sync::Lazy;
                    use fluent_static::{LanguageSpec, Message};

                    static SUPPORTED_LANGUAGES: &[&str] = &["en", "en-UK"];

                    static EN_RESOURCE: &str = "test=Test message\ntest-args1=Hello { $name }";
                    static EN_BUNDLE: Lazy<FluentBundle<FluentResource>> = Lazy::new(|| {
                        let lang_id = fluent_static::unic_langid::langid!("en");
                        let mut bundle: FluentBundle<FluentResource> = FluentBundle::new_concurrent(vec![lang_id]);
                        bundle.add_resource(FluentResource::try_new(EN_RESOURCE.to_string()).unwrap()).unwrap();
                        bundle
                    });

                    static EN_UK_RESOURCE: &str = "test=UK message\ntest-args1=Greetings { $name }";
                    static EN_UK_BUNDLE: Lazy<FluentBundle<FluentResource>> = Lazy::new(|| {
                        let lang_id = fluent_static::unic_langid::langid!("en-UK");
                        let mut bundle: FluentBundle<FluentResource> = FluentBundle::new_concurrent(vec![lang_id]);
                        bundle.add_resource(FluentResource::try_new(EN_UK_RESOURCE.to_string()).unwrap()).unwrap();
                        bundle
                    });

                    fn get_bundle(lang: &str) -> &'static FluentBundle<FluentResource> {
                        for common_lang in fluent_static::accept_language::intersection(lang, SUPPORTED_LANGUAGES) {
                            match common_lang.as_str() {
                                "en" => return &EN_BUNDLE,
                                "en-UK" => return &EN_UK_BUNDLE,
                                _ => continue,
                            }
                        };
                        & EN_BUNDLE
                    }

                    fn internal_message_format(bundle: &'static FluentBundle<FluentResource>, message_id: &str, args: Option<&FluentArgs>) -> Result<Message<'static>, FluentError> {
                        let msg = bundle.get_message(message_id).expect("Message not found");
                        let mut errors = vec![];
                        let result = Message::new(bundle.format_pattern(&msg.value().unwrap(), args, &mut errors));
                        if errors.is_empty() {
                            Ok(result)
                        } else {
                            Err(errors.into_iter().next().unwrap())
                        }
                    }


                    #[derive(Clone)]
                    pub struct MessagesBundle {
                        lang: LanguageSpec,
                        bundle: &'static FluentBundle<FluentResource>,
                    }

                    impl Into<LanguageSpec> for MessagesBundle {
                        fn into(self) -> LanguageSpec {
                            self.lang
                        }
                    }

                    impl From<LanguageSpec> for MessagesBundle {
                        fn from(value: LanguageSpec) -> Self {
                            Self {
                                lang: value.clone(),
                                bundle: get_bundle(value.as_ref())
                             }
                        }
                    }

                    impl AsRef<str> for MessagesBundle {
                        fn as_ref(&self) -> &str {
                            self.lang.as_ref()
                        }
                    }

                    impl MessagesBundle {
                        pub fn all_languages() -> &'static [&'static str] {
                            SUPPORTED_LANGUAGES
                        }

                        pub fn current_language(&self) -> &LanguageSpec {
                            &self.lang
                        }

                        pub fn test(&self) -> Message<'static> {
                            internal_message_format(self.bundle, "test", None)
                                .expect("Not fallible without variables; qed")
                        }

                        pub fn test_args_1<'a>(&self, name: impl Into<FluentValue<'a>>) -> Result<Message<'static>, FluentError> {
                            let mut args = FluentArgs::with_capacity(1);
                            args.set("name", name);
                            internal_message_format(self.bundle, "test-args1", Some(&args))
                        }
                    }

                }
            }
        };

        assert_eq!(expected.to_string(), actual.to_string());
    }
}