ankurah-derive 0.9.2

Ankurah Derive - Derive macros for Ankurah
Documentation
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
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
//! Active type wrapper generation for WASM bindings.
//!
//! Active types (LWW, Yrs, etc.) need WASM wrappers because wasm-bindgen doesn't support
//! generics. This module handles:
//! - Wrapper struct generation (e.g., `LWWString`, `Connection_LWWRefSession`)
//! - Method generation with proper TypeScript types
//! - `Ref<T>` → `TRef` conversion for type-safe entity references

use proc_macro2::TokenStream;
use quote::{format_ident, quote};
use regex::Regex;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use syn::Type;

// --- Type string helpers for Ref<T> handling ---

/// Rewrite `Ref<Model>` → `<Model as Model>::RefWrapper` for proper TS typing.
fn convert_ref_to_wrapper(type_str: &str) -> String {
    Regex::new(r"Ref<(\w+)>")
        .unwrap()
        .replace_all(type_str, |caps: &regex::Captures| format!("<{} as ::ankurah::model::Model>::RefWrapper", &caps[1]))
        .to_string()
}

/// Check for `Option<Ref<T>>` pattern.
fn has_option_ref(type_str: &str) -> bool { Regex::new(r"Option<\s*Ref<\w+>").unwrap().is_match(type_str) }

/// Check for bare `Ref<T>` (not wrapped in Option).
fn has_bare_ref(type_str: &str) -> bool { type_str.contains("Ref<") && !has_option_ref(type_str) }

/// Extract model name from `Ref<Model>` (e.g., `"Ref<User>"` → `Some("User")`).
fn extract_ref_model_name(type_str: &str) -> Option<String> {
    Regex::new(r"Ref<(\w+)>").unwrap().captures(type_str).map(|caps| caps[1].to_string())
}

/// Backend configuration for code generation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BackendConfig {
    pub backend_name: String,
    pub namespace: String,
    pub provided_wrapper_types: Vec<String>,
    /// Optional separate list for UniFFI-compatible types. If None, uses provided_wrapper_types.
    #[serde(default)]
    pub uniffi_provided_wrapper_types: Option<Vec<String>>,
    pub substitutions: HashMap<String, HashMap<String, String>>,
    pub values: Vec<ValueConfig>,
}

/// Configuration for a specific value type within a backend
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValueConfig {
    pub type_pattern: String,
    pub fully_qualified_type: String,
    pub accepts: String,
    pub generic_params: Vec<String>,
    pub materialized_pattern: String,
    pub methods: Vec<Method>,
}

/// Method configuration for code generation
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Method {
    pub name: String,
    pub args: Vec<(String, String)>, // (name, type)
    pub return_type: String,
    #[serde(default = "default_true")]
    pub wasm: bool,
    #[serde(default = "default_true")]
    pub uniffi: bool,
}

fn default_true() -> bool { true }

/// Describes how to generate wrappers for a specific active field type
pub struct ActiveTypeDesc {
    pub(crate) backend_config: BackendConfig,
    pub(crate) value_config: ValueConfig,               // The specific ValueConfig that matched
    pub(crate) concrete_types: HashMap<String, String>, // {T} -> Complex, etc.
}

impl ActiveTypeDesc {
    /// Create an ActiveTypeDesc from config, value config, and concrete types
    pub fn new(backend_config: BackendConfig, value_config: ValueConfig, concrete_types: HashMap<String, String>) -> Self {
        Self { backend_config, value_config, concrete_types }
    }

    /// Get the wrapper type name for WASM bindings (just the identifier)
    pub fn wrapper_type_name(&self) -> String {
        let mut pattern = self.value_config.materialized_pattern.clone();

        // Substitute all generic parameters with their concrete types
        for param in &self.value_config.generic_params {
            if let Some(concrete_type) = self.concrete_types.get(param) {
                let placeholder = format!("{{{}}}", param);
                // Strip non-alphanumeric characters from each concrete type
                let sanitized_type: String = concrete_type.chars().filter(|c| c.is_alphanumeric()).collect();
                pattern = pattern.replace(&placeholder, &sanitized_type);
            }
        }

        pattern
    }

    /// Get a model-scoped wrapper type name for WASM bindings.
    /// This includes the model name to avoid collisions when multiple models use
    /// the same custom type (e.g., Ref<Artist> in both Album and Track).
    /// Format: {ModelName}_{BaseWrapperName} e.g., "Album_LWWRefArtist"
    pub fn wrapper_type_name_for_model(&self, model_name: &str) -> String { format!("{}_{}", model_name, self.wrapper_type_name()) }

    /// Get the fully qualified wrapper type path for FFI bindings
    pub fn wrapper_type_path(&self, context: &str) -> String {
        let wrapper_name = self.wrapper_type_name();

        match context {
            "local" => {
                // For provided types generated by impl_provided_wrapper_types!()
                // The ffi module contents are re-exported at the parent level via `pub use ffi::*;`
                format!("{}::{}", self.backend_config.namespace, wrapper_name)
            }
            "external" => {
                // For custom types generated by impl_wrapper_type!() in current module
                wrapper_name
            }
            _ => wrapper_name,
        }
    }

    /// Determine if this type is provided by the backend or custom
    pub fn is_provided_type(&self) -> bool {
        // Check if any of the concrete types are in the provided_wrapper_types list
        for concrete_type in self.concrete_types.values() {
            if self.backend_config.provided_wrapper_types.contains(concrete_type) {
                return true;
            }
        }
        false
    }

    /// Get the appropriate fully qualified wrapper type path (used in tests)
    #[allow(unused)]
    pub fn get_wrapper_type_path(&self) -> String {
        if self.is_provided_type() {
            self.wrapper_type_path("local")
        } else {
            self.wrapper_type_path("external")
        }
    }

    /// Get the wrapper type for WASM bindings
    #[allow(unused)]
    pub fn wrapper_type(&self) -> syn::Result<syn::Type> {
        let wrapper_name = self.wrapper_type_name();
        syn::parse_str(&wrapper_name)
    }

    #[allow(unused)]
    pub fn rust_type_name(&self) -> String {
        let rust_type = self.rust_type().unwrap();
        quote!(#rust_type).to_string()
    }

    /// Get the fully qualified Rust type for accessor methods
    pub fn rust_type(&self) -> syn::Result<syn::Type> { self.rust_type_with_context("external") }

    /// Get the fully qualified Rust type for accessor methods with explicit context
    pub fn rust_type_with_context(&self, context: &str) -> syn::Result<syn::Type> {
        let mut type_str = self.value_config.fully_qualified_type.clone();

        // Apply context-specific substitutions first
        if let Some(context_substitutions) = self.backend_config.substitutions.get(context) {
            for (token, replacement) in context_substitutions {
                let placeholder = format!("{{{}}}", token);
                type_str = type_str.replace(&placeholder, replacement);
            }
        }

        // Substitute {T} with actual concrete types
        for (param, concrete_type) in &self.concrete_types {
            let placeholder = format!("{{{}}}", param);
            type_str = type_str.replace(&placeholder, concrete_type);
        }

        syn::parse_str(&type_str)
    }

    /// WASM methods for this active type wrapper.
    ///
    /// - `get()` → Projected value (e.g., `SessionRef` for `LWW<Ref<Session>>`)
    /// - `set(value)` → Accepts `TRef | TView` via duck typing on `.id` property
    ///
    /// Returns `(methods, ts_override)` - ts_override provides union type for set().
    fn wasm_methods(&self, context: &str) -> (Vec<TokenStream>, Option<String>) {
        let value_config = &self.backend_config.values[0];
        let substitute_fn = |backend: &ActiveTypeDesc, pattern: &str| backend.do_substitutions(pattern, context);

        let mut ts_set_override: Option<String> = None;

        let methods = value_config
            .methods
            .iter()
            .filter(|method| method.wasm)
            .map(|method| {
                let method_name = format_ident!("{}", method.name);

                // Check if any arg is a Ref<T> type for set method
                let ref_model_for_set: Option<String> = if method.name == "set" {
                    method.args.iter().find_map(|(_, arg_type)| {
                        let substituted = substitute_fn(self, arg_type);
                        if has_bare_ref(&substituted) {
                            extract_ref_model_name(&substituted)
                        } else {
                            None
                        }
                    })
                } else {
                    None
                };

                // For set with Ref<T>, accept JsValue and extract EntityId via duck typing
                // Accepts: ModelRef, ModelView (have .id), EntityId, or base64 string
                if let Some(ref model_name) = ref_model_for_set {
                    let model_ident = format_ident!("{}", model_name);
                    ts_set_override = Some(format!("{}Ref | {}View | string", model_name, model_name));

                    return quote! {
                        #[wasm_bindgen(skip_typescript)]
                        pub fn set(&self, value: JsValue) -> Result<(), JsValue> {
                            // Try multiple conversion strategies:
                            // 1. String -> parse as base64
                            // 2. EntityId -> use directly
                            // 3. Object with .id -> extract EntityId
                            let id: ::ankurah::proto::EntityId = if let Some(s) = value.as_string() {
                                ::ankurah::proto::EntityId::from_base64(&s)
                                    .map_err(|e| JsValue::from_str(&format!("Invalid EntityId string: {}", e)))?
                            } else if let Ok(id) = value.clone().try_into() {
                                id
                            } else {
                                let id_value = ::ankurah::derive_deps::js_sys::Reflect::get(&value, &JsValue::from_str("id"))
                                    .map_err(|_| JsValue::from_str("Expected string, EntityId, or object with 'id' property"))?;
                                id_value.try_into()
                                    .map_err(|_| JsValue::from_str("'id' property is not an EntityId"))?
                            };

                            let r: ::ankurah::property::Ref<#model_ident> = ::ankurah::property::Ref::new(id);
                            self.0.set(&r).map_err(|e| JsValue::from(e.to_string()))
                        }
                    };
                }

                // Regular method handling
                let args: Vec<TokenStream> = method
                    .args
                    .iter()
                    .map(|(arg_name, arg_type)| {
                        let arg_name = format_ident!("{}", arg_name);
                        let substituted = substitute_fn(self, arg_type);
                        let arg_type_str = convert_ref_to_wrapper(&substituted);
                        let arg_type: Type = syn::parse_str(&arg_type_str).expect("Failed to parse arg type");
                        quote! { #arg_name: #arg_type }
                    })
                    .collect();

                let original_return_type_str = substitute_fn(self, &method.return_type);
                let return_has_ref = original_return_type_str.contains("Ref<");
                let return_has_option_ref = has_option_ref(&original_return_type_str);
                let return_type_str = convert_ref_to_wrapper(&original_return_type_str);

                let arg_names: Vec<syn::Ident> = method.args.iter().map(|(name, _)| format_ident!("{}", name)).collect();
                let converted_args: Vec<TokenStream> = method
                    .args
                    .iter()
                    .zip(arg_names.iter())
                    .map(|((_, arg_type), arg_name)| {
                        let substituted = substitute_fn(self, arg_type);
                        let is_ref_arg = has_bare_ref(&substituted);
                        let is_option_ref_arg = has_option_ref(&substituted);
                        if arg_type == "{T}" && method.name == "set" {
                            if is_option_ref_arg {
                                quote! { &#arg_name.map(Into::into) }
                            } else if is_ref_arg {
                                quote! { &(#arg_name.into()) }
                            } else {
                                quote! { &#arg_name }
                            }
                        } else if is_option_ref_arg {
                            quote! { #arg_name.map(Into::into) }
                        } else if is_ref_arg {
                            quote! { #arg_name.into() }
                        } else {
                            quote! { #arg_name }
                        }
                    })
                    .collect();

                let (wasm_return_type_str, method_call) = if return_type_str.starts_with("Result<") {
                    let inner = return_type_str.strip_prefix("Result<").unwrap().strip_suffix(">").unwrap();
                    let ok_type = inner.split(", ").next().unwrap();
                    let call = if return_has_option_ref {
                        quote! { self.0.#method_name(#(#converted_args),*).map(|opt| opt.map(Into::into)).map_err(|e| ::wasm_bindgen::JsValue::from(e.to_string())) }
                    } else if return_has_ref {
                        quote! { self.0.#method_name(#(#converted_args),*).map(Into::into).map_err(|e| ::wasm_bindgen::JsValue::from(e.to_string())) }
                    } else {
                        quote! { self.0.#method_name(#(#converted_args),*).map_err(|e| ::wasm_bindgen::JsValue::from(e.to_string())) }
                    };
                    (format!("Result<{}, ::wasm_bindgen::JsValue>", ok_type), call)
                } else if return_has_option_ref {
                    (return_type_str.clone(), quote! { self.0.#method_name(#(#converted_args),*).map(Into::into) })
                } else if return_has_ref {
                    (return_type_str.clone(), quote! { self.0.#method_name(#(#converted_args),*).into() })
                } else {
                    (return_type_str.clone(), quote! { self.0.#method_name(#(#converted_args),*) })
                };

                let wasm_return_type: Type = syn::parse_str(&wasm_return_type_str).expect("Failed to parse return type");
                quote! {
                    pub fn #method_name(&self, #(#args),*) -> #wasm_return_type {
                        #method_call
                    }
                }
            })
            .collect();

        (methods, ts_set_override)
    }

    /// Generate WASM wrapper struct and impl block.
    /// Called when ankurah-derive is compiled with the `wasm` feature.
    #[cfg(feature = "wasm")]
    pub fn wasm_wrapper(&self, context: &str, model_scope: Option<&str>) -> TokenStream {
        let wrapper_name_str = match model_scope {
            Some(model) => self.wrapper_type_name_for_model(model),
            None => self.wrapper_type_name(),
        };
        let wrapper_name = format_ident!("{}", wrapper_name_str);
        let original_type: Type = self.rust_type_with_context(context).expect("Failed to parse original type");

        let (wasm_methods, ts_set_override) = self.wasm_methods(context);

        let ts_custom_section = if let Some(ref union_type) = ts_set_override {
            let ts_decl = format!("interface {} {{ set(value: {}): void; }}", wrapper_name_str, union_type);
            quote! {
                #[wasm_bindgen(typescript_custom_section)]
                const _: &'static str = #ts_decl;
            }
        } else {
            quote! {}
        };

        quote! {
            #[wasm_bindgen]
            pub struct #wrapper_name(
                #[wasm_bindgen(skip)]
                pub #original_type
            );

            #[wasm_bindgen]
            impl #wrapper_name {
                #(#wasm_methods)*
            }

            #ts_custom_section
        }
    }

    /// Generate UniFFI wrapper struct and impl block.
    /// Called when ankurah-derive is compiled with the `uniffi` feature (and wasm is not enabled).
    #[cfg(all(feature = "uniffi", not(feature = "wasm")))]
    pub fn uniffi_wrapper(&self, context: &str, model_scope: Option<&str>) -> TokenStream {
        let wrapper_name_str = match model_scope {
            Some(model) => self.wrapper_type_name_for_model(model),
            None => self.wrapper_type_name(),
        };
        let wrapper_name = format_ident!("{}", wrapper_name_str);
        let original_type: Type = self.rust_type_with_context(context).expect("Failed to parse original type");

        let uniffi_methods = self.uniffi_methods(context);

        quote! {
            #[derive(::uniffi::Object)]
            pub struct #wrapper_name(pub #original_type);

            #[::uniffi::export]
            impl #wrapper_name {
                #(#uniffi_methods)*
            }
        }
    }

    /// Stub for wasm_wrapper when wasm feature is not enabled
    #[cfg(not(feature = "wasm"))]
    pub fn wasm_wrapper(&self, _context: &str, _model_scope: Option<&str>) -> TokenStream {
        quote! {}
    }

    /// Stub for uniffi_wrapper when uniffi feature is not enabled (or wasm takes precedence)
    #[cfg(any(not(feature = "uniffi"), feature = "wasm"))]
    pub fn uniffi_wrapper(&self, _context: &str, _model_scope: Option<&str>) -> TokenStream {
        quote! {}
    }

    /// UniFFI methods - generates methods with PropertyError for error handling.
    /// PropertyError has #[uniffi(flat_error)] so it serializes via ToString.
    fn uniffi_methods(&self, context: &str) -> Vec<TokenStream> {
        let substitute_fn = |backend: &ActiveTypeDesc, pattern: &str| backend.do_substitutions(pattern, context);

        self.value_config.methods.iter().filter(|method| method.uniffi).map(|method| {
            let method_name = format_ident!("{}", method.name);

            // Special case: set with Ref<T> or Option<Ref<T>>
            if method.name == "set" {
                let substituted_arg = method.args.iter().find_map(|(_, arg_type)| {
                    let substituted = substitute_fn(self, arg_type);
                    if substituted.contains("Ref<") { Some(substituted) } else { None }
                });
                if let Some(ref substituted) = substituted_arg {
                    if let Some(model_name) = extract_ref_model_name(substituted) {
                        let model_ident = format_ident!("{}", model_name);
                        if has_option_ref(substituted) {
                            // Option<Ref<T>> -> Option<String>
                            return quote! {
                                pub fn set(&self, value: Option<String>) -> Result<(), ::ankurah::property::PropertyError> {
                                    let r: Option<::ankurah::property::Ref<#model_ident>> = match value {
                                        Some(ref s) => {
                                            let id = ::ankurah::proto::EntityId::from_base64(s)
                                                .map_err(|e| ::ankurah::property::PropertyError::InvalidValue {
                                                    value: s.clone(),
                                                    ty: format!("EntityId ({})", e)
                                                })?;
                                            Some(::ankurah::property::Ref::from(id))
                                        },
                                        None => None,
                                    };
                                    self.0.set(&r)
                                }
                            };
                        } else {
                            // Ref<T> -> String
                            return quote! {
                                pub fn set(&self, value: String) -> Result<(), ::ankurah::property::PropertyError> {
                                    let id = ::ankurah::proto::EntityId::from_base64(&value)
                                        .map_err(|e| ::ankurah::property::PropertyError::InvalidValue {
                                            value: value.clone(),
                                            ty: format!("EntityId ({})", e)
                                        })?;
                                    let r: ::ankurah::property::Ref<#model_ident> = ::ankurah::property::Ref::from(id);
                                    self.0.set(&r)
                                }
                            };
                        }
                    }
                }
            }

            // Build args (&str -> String for FFI)
            let args: Vec<TokenStream> = method.args.iter().map(|(arg_name, arg_type)| {
                let arg_name = format_ident!("{}", arg_name);
                let substituted = substitute_fn(self, arg_type);
                let arg_type_str = if substituted == "&str" { "String".to_string() } else { substituted };
                let arg_type: Type = syn::parse_str(&arg_type_str).expect("Failed to parse arg type");
                quote! { #arg_name: #arg_type }
            }).collect();

            let return_type_str = substitute_fn(self, &method.return_type);
            let return_has_option_ref = has_option_ref(&return_type_str);
            let return_has_bare_ref = has_bare_ref(&return_type_str);
            let arg_names: Vec<syn::Ident> = method.args.iter().map(|(name, _)| format_ident!("{}", name)).collect();

            let converted_args: Vec<TokenStream> = method.args.iter().zip(arg_names.iter()).map(|((_, arg_type), arg_name)| {
                let substituted = substitute_fn(self, arg_type);
                if substituted == "&str" || (arg_type == "{T}" && method.name == "set") { quote! { &#arg_name } } else { quote! { #arg_name } }
            }).collect();

            if return_type_str.starts_with("Result<") {
                let inner = return_type_str.strip_prefix("Result<").unwrap().strip_suffix(">").unwrap();
                let ok_type_str = inner.split(", ").next().unwrap();
                // Parse and use the original error type from the method signature
                let err_type_str = inner.split(", ").nth(1).unwrap_or("::ankurah::property::PropertyError");
                let err_type: Type = syn::parse_str(err_type_str).expect("Failed to parse error type");
                if return_has_option_ref {
                    // Result<Option<Ref<T>>, Err> -> Result<Option<String>, Err>
                    quote! { pub fn #method_name(&self, #(#args),*) -> Result<Option<String>, #err_type> { self.0.#method_name(#(#converted_args),*).map(|opt| opt.map(|r| r.id().to_base64())) } }
                } else if return_has_bare_ref {
                    // Result<Ref<T>, Err> -> Result<String, Err>
                    quote! { pub fn #method_name(&self, #(#args),*) -> Result<String, #err_type> { self.0.#method_name(#(#converted_args),*).map(|r| r.id().to_base64()) } }
                } else {
                    let ok_type: Type = syn::parse_str(ok_type_str).expect("Failed to parse ok type");
                    quote! { pub fn #method_name(&self, #(#args),*) -> Result<#ok_type, #err_type> { self.0.#method_name(#(#converted_args),*) } }
                }
            } else if return_has_option_ref {
                // Option<Ref<T>> -> Option<String>
                quote! { pub fn #method_name(&self, #(#args),*) -> Option<String> { self.0.#method_name(#(#converted_args),*).and_then(|r| Some(r.id().to_base64())) } }
            } else if return_has_bare_ref {
                quote! { pub fn #method_name(&self, #(#args),*) -> Option<String> { self.0.#method_name(#(#converted_args),*).map(|r| r.id().to_base64()) } }
            } else {
                let return_type: Type = syn::parse_str(&return_type_str).expect("Failed to parse return type");
                quote! { pub fn #method_name(&self, #(#args),*) -> #return_type { self.0.#method_name(#(#converted_args),*) } }
            }
        }).collect()
    }

    /// Substitute generic parameters in type/method signatures
    fn substitute_generics(&self, pattern: &str) -> String {
        let mut result = pattern.to_string();
        for (param, concrete_type) in &self.concrete_types {
            let placeholder = format!("{{{}}}", param);
            result = result.replace(&placeholder, concrete_type);
        }
        result
    }

    /// Substitute generic parameters and context-specific tokens
    fn do_substitutions(&self, pattern: &str, context: &str) -> String {
        let mut result = self.substitute_generics(pattern);

        // Apply context-specific substitutions
        if let Some(context_substitutions) = self.backend_config.substitutions.get(context) {
            for (token, replacement) in context_substitutions {
                let placeholder = format!("{{{}}}", token);
                result = result.replace(&placeholder, replacement);
            }
        }

        result
    }
}

#[cfg(test)]
mod tests {
    use maplit::hashmap;

    use super::*;

    #[test]
    fn test_materialized_name_simple() {
        let backend_config = BackendConfig {
            backend_name: "LWW".to_string(),
            namespace: "test".to_string(),
            provided_wrapper_types: vec![],
            uniffi_provided_wrapper_types: None,
            substitutions: HashMap::new(),
            values: vec![],
        };

        let value_config = ValueConfig {
            type_pattern: "LWW(?:<(.+)>)?".to_string(),
            fully_qualified_type: "LWW<{T}>".to_string(),
            accepts: ".*".to_string(),
            generic_params: vec!["T".to_string()],
            materialized_pattern: "LWW{T}".to_string(),
            methods: vec![],
        };

        let desc = ActiveTypeDesc::new(backend_config.clone(), value_config.clone(), hashmap! { "T".into() => "String".into() });
        assert_eq!(desc.wrapper_type_name(), "LWWString");

        let desc =
            ActiveTypeDesc::new(backend_config.clone(), value_config.clone(), hashmap! { "T".into() => "HashMap<String, i32>".into() });
        assert_eq!(desc.wrapper_type_name(), "LWWHashMapStringi32");
    }
}