facet_generate 0.17.2

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
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
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
//! AST-to-Kotlin source rendering.
//!
//! This module implements [`Emitter<Kotlin>`](super::super::Emitter) for each
//! node type in the format AST, turning abstract type descriptions into
//! idiomatic Kotlin code.
//!
//! # Emitter implementations
//!
//! | AST node | Kotlin output |
//! |---|---|
//! | [`Module`] | `package` declaration, `import` statements, feature helpers |
//! | [`Container`] | `data class`, `data object`, `sealed interface`, or `enum class` |
//! | [`Named<Format>`](Named) | A single `val` property declaration |
//! | [`Format`] | An inline type expression (`Int`, `List<String>`, `Pair<A, B>`, …) |
//! | [`Doc`] | `///` doc comments |
//! | `(Named<VariantFormat>, VariantContext)` | An enum/sealed-interface variant |
//!
//! # Kotlin type mapping
//!
//! The [`Format`] emitter maps Rust/reflection types to Kotlin equivalents —
//! for example `I32` → `Int`, `Seq(T)` → `List<T>`, `Option(T)` → `T?`,
//! tuples of size 2/3 → `Pair`/`Triple`, and larger tuples to `NTupleN<…>`.
//!
//! # Plugin-dependent output
//!
//! The [`Kotlin`] language tag carries a list of [`EmitterPlugin`]s. All
//! encoding-specific behaviour is delegated to those plugins — the emitter
//! itself contains no encoding checks. For example:
//!
//! - `JsonPlugin` supplies `@Serializable` / `@SerialName` type annotations
//!   and inline `@SerialName` annotations for all-unit enum class variants.
//! - `BincodePlugin` supplies `serialize` / `deserialize` methods and
//!   convenience `bincodeSerialize` / `bincodeDeserialize` wrappers.
//! - With no plugins, only plain type declarations are emitted.
//!
//! # Feature helpers
//!
//! The encoding-independent `TupleArray` helper (`buildList` polyfill for
//! Kotlin < 1.6.0) is inlined here as [`FEATURE_TUPLE_ARRAY`] and emitted
//! when [`Feature::TupleArray`] is set by [`CodeGeneratorConfig::update_from`].
//!
//! Bincode container helpers (`List<T>.serialize`, `Set<T>.serialize`, etc.)
//! are inlined in `BincodePlugin` (`generation/bincode/kotlin.rs`).
//! The JSON `BigInteger` `KSerializer` is inlined in `JsonPlugin`
//! (`generation/json/kotlin.rs`).

use std::{
    collections::BTreeMap,
    io::{Result, Write},
    string::ToString,
    sync::Arc,
};

use heck::ToLowerCamelCase;

use crate::{
    Registry,
    generation::{
        CodeGeneratorConfig, Container, Emitter, Feature,
        indent::{IndentWrite, Newlines},
        module::Module,
        plugin::{EmitContext, EmitterPlugin, VariantInfo},
    },
    reflection::format::{ContainerFormat, Doc, Format, Named, QualifiedTypeName, VariantFormat},
};

const FEATURE_TUPLE_ARRAY: &str = r"/**
 * Compatibility functions for buildList, ensuring support for Kotlin versions < 1.6.0
 *
 * These functions provide the same functionality as the standard library buildList functions
 * introduced in Kotlin 1.6.0. On Kotlin 1.6+, the compiler will prefer the standard library
 * versions due to better overload resolution, so these serve as fallbacks for older versions.
 *
 * The functions are inline and generate efficient bytecode equivalent to the standard library
 * implementations, so there's no performance penalty when included.
 */
inline fun <T> buildList(capacity: Int, builderAction: MutableList<T>.() -> Unit): List<T> {
    val list = ArrayList<T>(capacity)
    list.builderAction()
    return list
}

inline fun <T> buildList(builderAction: MutableList<T>.() -> Unit): List<T> {
    val list = mutableListOf<T>()
    list.builderAction()
    return list
}
";

/// Language tag for Kotlin code generation.
///
/// Passed as the `L` parameter to every [`Emitter<L>`](super::super::Emitter)
/// call. Carries a plugin list that controls all encoding-specific behaviour.
#[derive(Debug, Clone)]
pub struct Kotlin {
    pub(crate) config: CodeGeneratorConfig,
    pub(crate) plugins: Vec<Arc<dyn EmitterPlugin<Self>>>,
}

impl Kotlin {
    /// Create a Kotlin language tag with no default plugins.
    ///
    /// Use [`with_plugin`](Self::with_plugin) to attach plugins.
    #[must_use]
    pub fn new(config: &CodeGeneratorConfig, _registry: &Registry) -> Self {
        Self {
            config: config.clone(),
            plugins: vec![],
        }
    }

    /// Access the generator config.
    #[must_use]
    pub const fn config(&self) -> &CodeGeneratorConfig {
        &self.config
    }

    /// Add a plugin to this language tag, returning the modified tag.
    ///
    /// Plugins are invoked in the order they are added.
    #[must_use]
    pub fn with_plugin(mut self, plugin: Arc<dyn EmitterPlugin<Self>>) -> Self {
        self.plugins.push(plugin);
        self
    }

    /// Access the plugin list.
    #[must_use]
    pub fn plugins(&self) -> &[Arc<dyn EmitterPlugin<Self>>] {
        &self.plugins
    }
}

impl Emitter<Kotlin> for Module {
    fn write<W: IndentWrite>(&self, w: &mut W, lang: &Kotlin) -> Result<()> {
        let CodeGeneratorConfig {
            module_name,
            features,
            ..
        } = self.config();

        writeln!(w, "package {module_name}")?;
        writeln!(w)?;

        // --- Imports ---
        // Language-level imports that are NOT driven by plugins stay here.
        // Bincode imports are now provided by BincodePlugin::imports().
        let mut imports: Vec<String> = vec![];

        // --- Feature-driven imports (non-plugin) ---
        let mut features_out = vec![];
        for feature in features {
            match feature {
                Feature::BigInt => {
                    // `import java.math.BigInteger` is needed regardless of plugins,
                    // including when no plugin runs.
                    // Plugin-specific BigInt imports (JSON KSerializer, Bincode
                    // Int128) are added by their respective plugins.
                    imports.push("import java.math.BigInteger".to_string());
                }
                Feature::TupleArray => {
                    // TupleArray is encoding-independent — stays in the emitter.
                    write!(features_out, "{FEATURE_TUPLE_ARRAY}")?;
                    writeln!(features_out)?;
                }
                // Bincode feature helpers (ListOfT, SetOfT, MapOfT, OptionOfT, Bytes)
                // are now provided by BincodePlugin::module_helpers() / imports().
                _ => {}
            }
        }

        // --- Plugin imports ---
        for plugin in lang.plugins() {
            imports.extend(plugin.imports(self.config()));
        }

        // --- Plugin module helpers ---
        {
            let mut fw = w.child(&mut features_out);
            for plugin in lang.plugins() {
                plugin.module_helpers(&mut fw, self.config())?;
            }
        }

        let mut imports = imports
            .iter()
            .map(ToString::to_string)
            .collect::<Vec<String>>();

        imports.sort_unstable();
        imports.dedup();
        if !imports.is_empty() {
            for import in imports {
                writeln!(w, "{import}")?;
            }
            writeln!(w)?;
        }

        w.write_all(&features_out)?;

        Ok(())
    }
}

impl Emitter<Kotlin> for Container<'_> {
    fn write<W: IndentWrite>(&self, w: &mut W, lang: &Kotlin) -> Result<()> {
        let Container {
            name: QualifiedTypeName { namespace: _, name },
            format,
            ..
        } = self;
        match format {
            ContainerFormat::UnitStruct(doc) => {
                data_object(w, name, None, doc, lang, None)?;
            }
            ContainerFormat::NewTypeStruct(format, doc) => {
                data_class(
                    w,
                    name,
                    None,
                    &[Named::new(format, "value".to_string())],
                    doc,
                    lang,
                    None,
                )?;
            }
            ContainerFormat::TupleStruct(formats, doc) => {
                data_class(w, name, None, &named(formats), doc, lang, None)?;
            }
            ContainerFormat::Struct(fields, doc) => {
                if fields.is_empty() {
                    data_object(w, name, None, doc, lang, None)?;
                } else {
                    data_class(w, name, None, fields, doc, lang, None)?;
                }
            }
            ContainerFormat::Enum(variants, doc) => {
                let variant_list: Vec<_> = variants.values().cloned().collect();

                let all_unit_variants = variants
                    .values()
                    .all(|variant| matches!(variant.value, VariantFormat::Unit));

                if all_unit_variants {
                    enum_class(w, name, variants, doc, lang, self)?;
                } else {
                    sealed_interface(w, name, &variant_list, doc, lang, self)?;
                }
            }
        }

        Ok(())
    }
}

impl Emitter<Kotlin> for Named<Format> {
    fn write<W: IndentWrite>(&self, w: &mut W, lang: &Kotlin) -> Result<()> {
        self.doc.write(w, lang)?;

        let name = &self.name.to_lower_camel_case();
        write!(w, "val {name}: ")?;

        self.value.write(w, lang)?;

        // Add = null default only for top-level Option types
        if matches!(self.value, Format::Option(_)) {
            write!(w, " = null")?;
        }

        writeln!(w, ",")
    }
}

impl Emitter<Kotlin> for Doc {
    fn write<W: IndentWrite>(&self, w: &mut W, _lang: &Kotlin) -> Result<()> {
        for comment in self.comments() {
            writeln!(w, "/// {comment}")?;
        }

        Ok(())
    }
}

/// Tells a variant emitter whether it is being written inside a
/// `sealed interface` or an `enum class`, since the Kotlin syntax differs.
#[derive(Clone)]
pub enum VariantContext {
    /// Variant inside a `sealed interface` — carries the interface name and
    /// the variant's zero-based index (used as the bincode discriminant).
    SealedInterface(String, usize),
    /// Variant inside an `enum class` (all-unit variants only).
    EnumClass,
}

impl Emitter<Kotlin> for (&Named<VariantFormat>, &VariantContext) {
    #[allow(clippy::too_many_lines)]
    fn write<W: IndentWrite>(&self, w: &mut W, lang: &Kotlin) -> Result<()> {
        let (
            Named {
                name,
                doc,
                value: format,
            },
            context,
        ) = self;

        match (&format, context) {
            (VariantFormat::Variable(_), _) => {
                unreachable!("placeholders should not get this far")
            }
            (VariantFormat::Unit, VariantContext::SealedInterface(interface_name, index)) => {
                data_object(w, name, Some(interface_name), doc, lang, Some(*index))?;
            }
            (VariantFormat::Unit, VariantContext::EnumClass) => {
                doc.write(w, lang)?;
                let name_upper = name.to_uppercase();
                let prefix_parts: Vec<String> = lang
                    .plugins()
                    .iter()
                    .flat_map(|p| p.enum_variant_annotations(name))
                    .collect();
                if prefix_parts.is_empty() {
                    write!(w, "{name_upper}")?;
                } else {
                    let prefix = prefix_parts.join(" ");
                    write!(w, "{prefix} {name_upper}")?;
                }
            }
            (
                VariantFormat::NewType(inner),
                VariantContext::SealedInterface(interface_name, index),
            ) => {
                data_class(
                    w,
                    name,
                    Some(interface_name),
                    &[Named::new(inner, "value".to_string())],
                    doc,
                    lang,
                    Some(*index),
                )?;
            }
            (VariantFormat::NewType(_format), VariantContext::EnumClass) => {
                unreachable!("NewType variants are not supported in enum classes")
            }
            (
                VariantFormat::Tuple(formats),
                VariantContext::SealedInterface(interface_name, index),
            ) => {
                data_class(
                    w,
                    name,
                    Some(interface_name),
                    &named(formats),
                    doc,
                    lang,
                    Some(*index),
                )?;
            }
            (VariantFormat::Tuple(_formats), VariantContext::EnumClass) => {
                unreachable!("Tuple variants are not supported in enum classes")
            }
            (
                VariantFormat::Struct(fields),
                VariantContext::SealedInterface(interface_name, index),
            ) => {
                data_class(
                    w,
                    name,
                    Some(interface_name),
                    fields,
                    doc,
                    lang,
                    Some(*index),
                )?;
            }
            (VariantFormat::Struct(_fields), VariantContext::EnumClass) => {
                unreachable!("Struct variants are not supported in enum classes")
            }
        }

        Ok(())
    }
}

impl Emitter<Kotlin> for Format {
    fn write<W: IndentWrite>(&self, w: &mut W, lang: &Kotlin) -> Result<()> {
        match &self {
            Self::Variable(_variable) => unreachable!("placeholders should not get this far"),
            Self::TypeName(qualified_type_name) => {
                write!(
                    w,
                    "{ty}",
                    ty = qualified_type_name.format(ToString::to_string, ".")
                )
            }
            Self::Unit => write!(w, "Unit"),
            Self::Bool => write!(w, "Boolean"),
            Self::I8 => write!(w, "Byte"),
            Self::I16 => write!(w, "Short"),
            Self::I32 => write!(w, "Int"),
            Self::I64 => write!(w, "Long"),
            Self::U8 => write!(w, "UByte"),
            Self::U16 => write!(w, "UShort"),
            Self::U32 => write!(w, "UInt"),
            Self::U64 => write!(w, "ULong"),
            Self::I128 | Self::U128 => write!(w, "BigInteger"),
            Self::F32 => write!(w, "Float"),
            Self::F64 => write!(w, "Double"),
            Self::Char | Self::Str => write!(w, "String"),
            Self::Bytes => write!(w, "Bytes"),
            Self::Uuid => write!(w, "UUID"),

            Self::Option(format) => {
                format.write(w, lang)?;
                write!(w, "?")
            }
            Self::Seq(format) => {
                write!(w, "List<")?;
                format.write(w, lang)?;
                write!(w, ">")
            }
            Self::Set(format) => {
                write!(w, "Set<")?;
                format.write(w, lang)?;
                write!(w, ">")
            }
            Self::Map { key, value } => {
                write!(w, "Map<")?;
                key.write(w, lang)?;
                write!(w, ", ")?;
                value.write(w, lang)?;
                write!(w, ">")
            }
            Self::Tuple(formats) => {
                let len = formats.len();
                match len {
                    0 => write!(w, "Unit"),
                    1 => {
                        // A single-element tuple is just the element itself
                        formats[0].write(w, lang)
                    }
                    2 => {
                        write!(w, "Pair<")?;
                        formats[0].write(w, lang)?;
                        write!(w, ", ")?;
                        formats[1].write(w, lang)?;
                        write!(w, ">")
                    }
                    3 => {
                        write!(w, "Triple<")?;
                        formats[0].write(w, lang)?;
                        write!(w, ", ")?;
                        formats[1].write(w, lang)?;
                        write!(w, ", ")?;
                        formats[2].write(w, lang)?;
                        write!(w, ">")
                    }
                    _ => {
                        // For larger tuples, we'll use a data class NTupleN
                        write!(w, "NTuple{len}<")?;
                        for (i, format) in formats.iter().enumerate() {
                            if i > 0 {
                                write!(w, ", ")?;
                            }
                            format.write(w, lang)?;
                        }
                        write!(w, ">")
                    }
                }
            }
            Self::TupleArray { content, size: _ } => {
                write!(w, "List<")?;
                content.write(w, lang)?;
                write!(w, ">")
            }
        }
    }
}

/// Emits a Kotlin `data object` — used for unit structs and unit variants.
///
/// When `interface` is `Some`, the object implements it (i.e. it is a variant
/// inside a `sealed interface`). Encoding-specific body code (e.g. serialize /
/// deserialize methods) is delegated to plugins via the `type_body` hook.
fn data_object<W: IndentWrite>(
    w: &mut W,
    name: &str,
    interface: Option<&str>,
    doc: &Doc,
    lang: &Kotlin,
    variant_index: Option<usize>,
) -> Result<()> {
    doc.write(w, lang)?;

    write_plugin_annotations(w, name, lang)?;

    write!(w, "data object {name}")?;

    if let Some(interface) = interface {
        write!(w, ": {interface}")?;
    }

    // Plugin type body
    {
        let temp_name = QualifiedTypeName::root(name.to_string());
        let temp_format = ContainerFormat::UnitStruct(Doc::default());
        let temp_container = Container {
            name: &temp_name,
            format: &temp_format,
        };
        let variant_format = VariantFormat::Unit;
        let ctx = if let (Some(parent_name), Some(index)) = (interface, variant_index) {
            EmitContext::for_variant(
                &temp_container,
                &lang.config,
                VariantInfo {
                    name,
                    index,
                    format: &variant_format,
                    fields: &[],
                    parent_name,
                },
            )
        } else {
            EmitContext::top_level(&temp_container, &lang.config)
        };
        write_plugin_body(w, lang, &ctx)?;
    }

    Ok(())
}

/// Emits a Kotlin `data class` — used for structs (with fields), newtype
/// structs, tuple structs, and non-unit sealed-interface variants.
///
/// When `interface` is `Some`, the class implements it. Encoding-specific
/// body code (e.g. serialize / deserialize methods) is delegated to plugins
/// via the `type_body` hook.
fn data_class<W: IndentWrite>(
    w: &mut W,
    name: &str,
    interface: Option<&str>,
    fields: &[Named<Format>],
    doc: &Doc,
    lang: &Kotlin,
    variant_index: Option<usize>,
) -> Result<()> {
    doc.write(w, lang)?;

    write_plugin_annotations(w, name, lang)?;

    writeln!(w, "data class {name}(")?;

    w.indent();
    for field in fields {
        field.write(w, lang)?;
    }
    w.unindent();

    write!(w, ")")?;

    if let Some(interface) = interface {
        write!(w, " : {interface}")?;
    }

    // Plugin type body
    {
        let temp_name = QualifiedTypeName::root(name.to_string());
        let temp_format = ContainerFormat::Struct(fields.to_vec(), Doc::default());
        let temp_container = Container {
            name: &temp_name,
            format: &temp_format,
        };
        let variant_format = VariantFormat::Struct(fields.to_vec());
        let ctx = if let (Some(parent_name), Some(index)) = (interface, variant_index) {
            EmitContext::for_variant(
                &temp_container,
                &lang.config,
                VariantInfo {
                    name,
                    index,
                    format: &variant_format,
                    fields,
                    parent_name,
                },
            )
        } else {
            EmitContext::top_level(&temp_container, &lang.config)
        };
        write_plugin_body(w, lang, &ctx)?;
    }

    Ok(())
}

/// Emits a Kotlin `enum class` — used when all variants are unit variants.
///
/// Encoding-specific annotations (e.g. `@SerialName` for JSON) are handled
/// by the variant emitter; type-body code is delegated to plugins.
fn enum_class<W: IndentWrite>(
    w: &mut W,
    name: &str,
    variants: &BTreeMap<u32, Named<VariantFormat>>,
    doc: &Doc,
    lang: &Kotlin,
    container: &Container,
) -> Result<()> {
    doc.write(w, lang)?;

    write_plugin_annotations(w, name, lang)?;

    write!(w, "enum class {name} ")?;
    let mut w = w.block(Newlines::BOTH)?;

    for (i, variant) in variants {
        if *i > 0 {
            writeln!(w, ",")?;
        }

        (variant, &VariantContext::EnumClass).write(&mut w, lang)?;
    }
    writeln!(w, ";")?;

    // Plugin type body (e.g. JSON serialName accessor)
    {
        let ctx = EmitContext::top_level(container, &lang.config);
        for plugin in lang.plugins() {
            plugin.type_body(&mut w as &mut dyn IndentWrite, &ctx)?;
        }
    }

    Ok(())
}

/// Emits a Kotlin `sealed interface` — used when at least one variant
/// carries data (newtype, tuple, or struct variant).
///
/// Each variant becomes a nested `data class` or `data object` that
/// implements the interface. Encoding-specific body code (preamble and
/// companion objects) is delegated to plugins.
fn sealed_interface<W: IndentWrite>(
    w: &mut W,
    name: &str,
    variants: &[Named<VariantFormat>],
    doc: &Doc,
    lang: &Kotlin,
    container: &Container,
) -> Result<()> {
    doc.write(w, lang)?;

    write_plugin_annotations(w, name, lang)?;

    write!(w, "sealed interface {name} ")?;
    let mut w = w.block(Newlines::BOTH)?;

    // Plugin type body preamble (before variants)
    {
        let ctx = EmitContext::top_level(container, &lang.config);
        for plugin in lang.plugins() {
            plugin.type_body_preamble(&mut w as &mut dyn IndentWrite, &ctx)?;
        }
    }

    for (index, variant) in variants.iter().enumerate() {
        if index > 0 {
            writeln!(w)?;
        }
        let ctx = VariantContext::SealedInterface(name.to_string(), index);
        (variant, &ctx).write(&mut w, lang)?;
    }

    // Plugin type body (after variants)
    {
        let ctx = EmitContext::top_level(container, &lang.config);
        for plugin in lang.plugins() {
            plugin.type_body(&mut w as &mut dyn IndentWrite, &ctx)?;
        }
    }

    Ok(())
}

/// Run plugin type-body hooks, opening a `{ }` block if any plugin needs one.
/// If no plugin needs a body, emits a plain newline instead.
fn write_plugin_body<W: IndentWrite>(w: &mut W, lang: &Kotlin, ctx: &EmitContext) -> Result<()> {
    let needs_body = lang.plugins().iter().any(|p| p.has_type_body(ctx));
    if needs_body {
        write!(w, " ")?;
        let mut w = w.block(Newlines::BOTH)?;
        for plugin in lang.plugins() {
            plugin.type_body(&mut w as &mut dyn IndentWrite, ctx)?;
        }
    } else {
        writeln!(w)?;
    }
    Ok(())
}

/// Emits plugin type annotations (e.g. `@Serializable`, `@SerialName`) for a
/// named type. Creates a temporary [`Container`] so that the plugin
/// [`EmitContext`] can be constructed without threading the real container
/// through every helper function.
fn write_plugin_annotations<W: IndentWrite>(w: &mut W, name: &str, lang: &Kotlin) -> Result<()> {
    if lang.plugins().is_empty() {
        return Ok(());
    }
    let temp_name = QualifiedTypeName::root(name.to_string());
    let temp_format = ContainerFormat::UnitStruct(Doc::default());
    let temp_container = Container {
        name: &temp_name,
        format: &temp_format,
    };
    let ctx = EmitContext::top_level(&temp_container, &lang.config);
    for plugin in lang.plugins() {
        for annotation in plugin.type_annotations(&ctx) {
            writeln!(w, "{annotation}")?;
        }
    }
    Ok(())
}

fn named<Format: Clone>(formats: &[Format]) -> Vec<Named<Format>> {
    formats
        .iter()
        .enumerate()
        .map(|(i, f)| Named::new(f, format!("field{i}")))
        .collect()
}

#[cfg(test)]
mod tests;
#[cfg(test)]
mod tests_bincode;
#[cfg(test)]
mod tests_json;