facet_generate 0.17.1

Generate Swift, Kotlin, TypeScript, and C# from types annotated with `#[derive(Facet)]`
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
//! Unit tests for [`SwiftCodeGenerator`] — import generation and qualified-name
//! resolution.
//!
//! Tests build small [`Registry`] values by hand (rather than via the
//! `reflect!` macro) so that module and external-package configurations can
//! be controlled precisely.
//!
//! # Coverage
//!
//! | Area | What is tested |
//! |------|----------------|
//! | Serde imports | `BincodePlugin` triggers `import Serde`; no plugin does not |
//! | External definitions | External namespaces appear as `import` statements |
//! | Plugin config | Plugins propagate through to generated output |
//! | Feature helpers | Complex types (e.g. `Seq`) trigger trait helper emission when a plugin is active |

use std::collections::BTreeMap;

use std::sync::Arc;

use crate::{
    generation::{CodeGeneratorConfig, bincode::BincodePlugin, plugin::EmitterPlugin},
    reflection::format::{ContainerFormat, Doc, Format, Named, QualifiedTypeName},
};

use super::*;
use crate::generation::swift::emitter::Swift;

fn generate(
    config: &CodeGeneratorConfig,
    plugins: Vec<Arc<dyn EmitterPlugin<Swift>>>,
    registry: &Registry,
) -> String {
    let generator = SwiftCodeGenerator::new(config).with_plugins(plugins);
    let mut output = Vec::new();
    generator.output(&mut output, registry).unwrap();
    String::from_utf8(output).unwrap()
}

#[test]
fn test_no_encoding_does_not_import_serde() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "id".to_string(),
        doc: Doc::new(),
        value: Format::U32,
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![], &registry);

    assert!(
        !output.contains("import Serde"),
        "Should not import Serde when encoding is None: {output}"
    );
}

#[test]
fn test_bincode_encoding_has_serde_import() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "name".to_string(),
        doc: Doc::new(),
        value: Format::Str,
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("import Serde"),
        "Bincode encoding should import Serde: {output}"
    );
}

#[test]
fn test_preamble_includes_external_definition_imports() {
    let mut external_definitions = BTreeMap::new();
    external_definitions.insert("another_target".to_string(), vec!["Child".to_string()]);

    let config = CodeGeneratorConfig::new("MyPackage".to_string())
        .with_external_definitions(external_definitions);

    let mut registry = Registry::new();
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::UnitStruct(Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("import AnotherTarget"),
        "Should import UpperCamelCase external definitions: {output}"
    );
    assert!(
        output.contains("import Serde"),
        "Should always import Serde when encoding is set: {output}"
    );
}

#[test]
fn test_trait_helpers_emitted_for_complex_types() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "items".to_string(),
        doc: Doc::new(),
        value: Format::Seq(Box::new(Format::Str)),
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("func serializeArray<T, S: Serializer>"),
        "Should emit generic array serialization helper: {output}"
    );
    assert!(
        output.contains("func deserializeArray<T, D: Deserializer>"),
        "Should emit generic array deserialization helper: {output}"
    );
}

#[test]
fn test_no_trait_helpers_without_encoding() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "items".to_string(),
        doc: Doc::new(),
        value: Format::Seq(Box::new(Format::Str)),
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![], &registry);

    assert!(
        !output.contains("func serializeArray"),
        "No encoding means no trait helpers: {output}"
    );
    assert!(
        !output.contains("func deserializeArray"),
        "No encoding means no trait helpers: {output}"
    );
}

#[test]
fn test_map_with_hashable_k_v_implement_hashable_and_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "items".to_string(),
        doc: Doc::new(),
        value: Format::Map {
            key: Box::new(Format::Str),
            value: Box::new(Format::Str),
        },
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("public struct MyStruct: Hashable, Equatable {"),
        "Struct is not hashable and equatable:\n{output}"
    );
}

#[test]
fn test_struct_with_hashable_scalar_implements_hashable_and_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "items".to_string(),
        doc: Doc::new(),
        value: Format::U8,
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("public struct MyStruct: Hashable, Equatable {"),
        "Struct is not hashable and equatable:\n{output}"
    );
}

#[test]
fn test_struct_with_hashable_map_implements_hashable_and_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let fields = vec![Named {
        name: "items".to_string(),
        doc: Doc::new(),
        value: Format::Map {
            key: Box::new(Format::Str),
            value: Box::new(Format::Str),
        },
    }];
    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("public struct MyStruct: Hashable, Equatable {"),
        "Struct is not hashable and equatable:\n{output}"
    );
}

#[test]
fn test_enum_with_hashable_variants_implements_hashable_and_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();
    let mut variants = BTreeMap::new();

    let str_variant = Named {
        name: "StrVariant".to_string(),
        doc: Doc::new(),
        value: VariantFormat::NewType(Box::new(Format::Str)),
    };

    variants.insert(0, str_variant);

    let map_variant = Named {
        name: "MapVariant".to_string(),
        doc: Doc::new(),
        value: VariantFormat::NewType(Box::new(Format::Map {
            key: Box::new(Format::Str),
            value: Box::new(Format::Str),
        })),
    };
    variants.insert(1, map_variant);

    registry.insert(
        QualifiedTypeName::root("MyEnum".to_string()),
        ContainerFormat::Enum(variants, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("indirect public enum MyEnum: Hashable, Equatable {"),
        "MyEnum is not hashable:\n{output}"
    );
}

#[test]
fn test_with_enum_and_struct_variant_implements_hashable_and_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();

    let fields = vec![
        Named {
            name: "str_item".to_string(),
            doc: Doc::new(),
            value: Format::Str,
        },
        Named {
            name: "str_map".to_string(),
            doc: Doc::new(),
            value: Format::Map {
                key: Box::new(Format::Str),
                value: Box::new(Format::Str),
            },
        },
        Named {
            name: "str_option".to_string(),
            doc: Doc::new(),
            value: Format::Option(Box::new(Format::Str)),
        },
    ];

    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let mut variants = BTreeMap::new();

    let str_variant = Named {
        name: "StrVariant".to_string(),
        doc: Doc::new(),
        value: VariantFormat::NewType(Box::new(Format::Str)),
    };

    variants.insert(0, str_variant);

    let struct_variant = Named {
        name: "StructVariant".to_string(),
        doc: Doc::new(),
        value: VariantFormat::NewType(Box::new(Format::TypeName(QualifiedTypeName {
            namespace: Namespace::Root,
            name: "MyStruct".to_string(),
        }))),
    };
    variants.insert(1, struct_variant);

    registry.insert(
        QualifiedTypeName::root("MyEnum".to_string()),
        ContainerFormat::Enum(variants, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("indirect public enum MyEnum: Hashable, Equatable {"),
        "MyEnum is not hashable:\n{output}"
    );
}

#[test]
fn test_type_cycle_is_hashable_and_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let mut registry = Registry::new();

    let fields = vec![Named {
        name: "str_item".to_string(),
        doc: Doc::new(),
        value: Format::Str,
    }];

    registry.insert(
        QualifiedTypeName::root("MyStruct".to_string()),
        ContainerFormat::Struct(fields, Doc::new()),
    );

    let mut variants = BTreeMap::new();

    let struct_variant = Named {
        name: "StructVariant".to_string(),
        doc: Doc::new(),
        value: VariantFormat::NewType(Box::new(Format::TypeName(QualifiedTypeName {
            namespace: Namespace::Root,
            name: "MyStruct".to_string(),
        }))),
    };

    let self_enum_variant = Named {
        name: "EnumVariant".to_string(),
        doc: Doc::new(),
        value: VariantFormat::NewType(Box::new(Format::TypeName(QualifiedTypeName {
            namespace: Namespace::Root,
            name: "MyEnum".to_string(),
        }))),
    };
    variants.insert(0, struct_variant);
    variants.insert(1, self_enum_variant);

    registry.insert(
        QualifiedTypeName::root("MyEnum".to_string()),
        ContainerFormat::Enum(variants, Doc::new()),
    );

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("indirect public enum MyEnum: Hashable, Equatable {"),
        "MyEnum is not hashable:\n{output}"
    );
}

#[test]
fn test_struct_declaration_easy_order() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());
    let fields = vec![
        Named {
            name: "items".to_string(),
            doc: Doc::new(),
            value: Format::Map {
                key: Box::new(Format::Str),
                value: Box::new(Format::Str),
            },
        },
        // MyStruct2, it will be added to the registry before MyStruct1
        Named {
            name: "struct_2".to_string(),
            doc: Doc::new(),
            value: Format::TypeName(QualifiedTypeName {
                namespace: Namespace::Root,
                name: "MyStruct2".to_string(),
            }),
        },
    ];
    let struct1 = ContainerFormat::Struct(fields.clone(), Doc::new());
    let struct2 = ContainerFormat::Struct(fields, Doc::new());

    let mut registry = Registry::new();

    registry.insert(QualifiedTypeName::root("MyStruct2".to_string()), struct2);
    registry.insert(QualifiedTypeName::root("MyStruct1".to_string()), struct1);

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("public struct MyStruct1: Hashable, Equatable {"),
        "MyStruct1 is not hashable and equatable:\n{output}"
    );
    assert!(
        output.contains("public struct MyStruct2: Hashable, Equatable {"),
        "MyStruct2 is not hashable and equatable:\n{output}"
    );
}

#[test]
fn test_struct_declaration_inv_order() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());
    let fields = vec![
        Named {
            name: "items".to_string(),
            doc: Doc::new(),
            value: Format::Map {
                key: Box::new(Format::Str),
                value: Box::new(Format::Str),
            },
        },
        // MyStruct2, will be added to the registry after MyStruct1
        Named {
            name: "struct_2".to_string(),
            doc: Doc::new(),
            value: Format::TypeName(QualifiedTypeName {
                namespace: Namespace::Root,
                name: "MyStruct2".to_string(),
            }),
        },
    ];
    let struct1 = ContainerFormat::Struct(fields.clone(), Doc::new());
    let struct2 = ContainerFormat::Struct(fields, Doc::new());

    let mut registry = Registry::new();

    registry.insert(QualifiedTypeName::root("MyStruct1".to_string()), struct1);
    registry.insert(QualifiedTypeName::root("MyStruct2".to_string()), struct2);

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("public struct MyStruct1: Hashable, Equatable {"),
        "MyStruct1 is not hashable and equatable:\n{output}"
    );
    assert!(
        output.contains("public struct MyStruct2: Hashable, Equatable {"),
        "MyStruct2 is not hashable and equatable:\n{output}"
    );
}

#[test]
#[allow(clippy::similar_names)]
fn test_mutual_recursion_equatable() {
    let config = CodeGeneratorConfig::new("MyPackage".to_string());

    let struct_a_fields = vec![
        Named {
            name: "value".to_string(),
            doc: Doc::new(),
            value: Format::U32,
        },
        Named {
            name: "other".to_string(),
            doc: Doc::new(),
            value: Format::TypeName(QualifiedTypeName {
                namespace: Namespace::Root,
                name: "StructB".to_string(),
            }),
        },
    ];

    let struct_b_fields = vec![
        Named {
            name: "value".to_string(),
            doc: Doc::new(),
            value: Format::U32,
        },
        Named {
            name: "other".to_string(),
            doc: Doc::new(),
            value: Format::TypeName(QualifiedTypeName {
                namespace: Namespace::Root,
                name: "StructA".to_string(),
            }),
        },
    ];

    let struct_a = ContainerFormat::Struct(struct_a_fields, Doc::new());
    let struct_b = ContainerFormat::Struct(struct_b_fields, Doc::new());

    let mut registry = Registry::new();
    registry.insert(QualifiedTypeName::root("StructA".to_string()), struct_a);
    registry.insert(QualifiedTypeName::root("StructB".to_string()), struct_b);

    let output = generate(&config, vec![Arc::new(BincodePlugin)], &registry);

    assert!(
        output.contains("public struct StructA: Hashable, Equatable {"),
        "StructA should be hashable and equatable:\n{output}"
    );
    assert!(
        output.contains("public struct StructB: Hashable, Equatable {"),
        "StructB should be hashable and equatable:\n{output}"
    );
}