ferogram-tl-gen 0.3.8

Build-time code generator: Telegram TL schema → Rust source
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
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.

use std::fs::File;
use std::io::{self, Write};
use std::path::Path;

use ferogram_tl_parser::tl::{Category, Definition, ParameterType};

use crate::grouper;
use crate::metadata::Metadata;
use crate::namegen as n;

/// Generation configuration.
pub struct Config {
    /// Emit `name_for_id(id) -> Option<&'static str>` in the common module.
    pub gen_name_for_id: bool,
    /// Also implement `Deserializable` for function types (useful for servers).
    pub deserializable_functions: bool,
    /// Derive `Debug` on all generated types.
    pub impl_debug: bool,
    /// Emit `From<types::Foo> for enums::Bar` impls.
    pub impl_from_type: bool,
    /// Emit `TryFrom<enums::Bar> for types::Foo` impls.
    pub impl_from_enum: bool,
    /// Derive `serde::{Serialize, Deserialize}` on all types.
    pub impl_serde: bool,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            gen_name_for_id: false,
            deserializable_functions: false,
            impl_debug: true,
            impl_from_type: true,
            impl_from_enum: true,
            impl_serde: false,
        }
    }
}

// Outputs

/// Writers for each generated Rust module.
pub struct Outputs<W: Write> {
    /// Receives the layer constant, `name_for_id`, etc.
    pub common: W,
    /// Receives `pub mod types { ... }` (concrete constructors as structs).
    pub types: W,
    /// Receives `pub mod functions { ... }` (RPC functions as structs).
    pub functions: W,
    /// Receives `pub mod enums { ... }` (boxed types as enums).
    pub enums: W,
}

impl Outputs<File> {
    /// Convenience constructor that opens files inside `out_dir`.
    pub fn from_dir(out_dir: &str) -> io::Result<Self> {
        let p = Path::new(out_dir);
        Ok(Self {
            common: File::create(p.join("generated_common.rs"))?,
            types: File::create(p.join("generated_types.rs"))?,
            functions: File::create(p.join("generated_functions.rs"))?,
            enums: File::create(p.join("generated_enums.rs"))?,
        })
    }
}

impl<W: Write> Outputs<W> {
    /// Flush all writers.
    pub fn flush(&mut self) -> io::Result<()> {
        self.common.flush()?;
        self.types.flush()?;
        self.functions.flush()?;
        self.enums.flush()
    }
}

// Special-cased primitives

/// These TL types are handled as Rust primitives; we never emit structs/enums.
const BUILTIN_TYPES: &[&str] = &["Bool", "True"];

fn is_builtin(ty_name: &str) -> bool {
    BUILTIN_TYPES.contains(&ty_name)
}

// Public API

/// Generate Rust source code from a slice of parsed TL definitions.
///
/// Write results into `outputs`. Call `outputs.flush()` when done.
pub fn generate<W: Write>(
    defs: &[Definition],
    config: &Config,
    outputs: &mut Outputs<W>,
) -> io::Result<()> {
    let meta = Metadata::build(defs);

    write_common(defs, config, &mut outputs.common)?;
    write_types_mod(defs, config, &meta, &mut outputs.types)?;
    write_functions_mod(defs, config, &meta, &mut outputs.functions)?;
    write_enums_mod(defs, config, &meta, &mut outputs.enums)?;

    Ok(())
}

// Common module

fn write_common<W: Write>(defs: &[Definition], config: &Config, out: &mut W) -> io::Result<()> {
    // Extract LAYER constant from the first `// LAYER N` comment heuristic
    // for now we derive it from the highest layer seen in definitions or emit 0.
    writeln!(out, "// @generated: do not edit by hand")?;
    writeln!(out, "// Re-run the build script to regenerate.")?;
    writeln!(out)?;
    writeln!(out, "/// The API layer this code was generated from.")?;
    writeln!(out, "pub const LAYER: i32 = 0; // update via build.rs")?;
    writeln!(out)?;

    if config.gen_name_for_id {
        writeln!(out, "/// Returns the TL name for a known constructor ID.")?;
        writeln!(
            out,
            "pub fn name_for_id(id: u32) -> Option<&'static str> {{"
        )?;
        writeln!(out, "    match id {{")?;
        for def in defs {
            writeln!(
                out,
                "        {:#010x} => Some(\"{}\"),",
                def.id,
                def.full_name()
            )?;
        }
        writeln!(out, "        _ => None,")?;
        writeln!(out, "    }}")?;
        writeln!(out, "}}")?;
    }

    Ok(())
}

// Struct generation (types + functions)

fn write_types_mod<W: Write>(
    defs: &[Definition],
    config: &Config,
    meta: &Metadata,
    out: &mut W,
) -> io::Result<()> {
    writeln!(out, "// @generated: do not edit by hand")?;
    writeln!(out, "pub mod types {{")?;

    let grouped = grouper::group_by_ns(defs, Category::Types);
    let mut namespaces: Vec<&String> = grouped.keys().collect();
    namespaces.sort();

    for ns in namespaces {
        let bucket = &grouped[ns];
        let indent: String = if ns.is_empty() {
            "    ".to_owned()
        } else {
            writeln!(out, "    pub mod {ns} {{")?;
            "        ".to_owned()
        };

        for def in bucket {
            write_struct(out, &indent, def, meta, config)?;
            write_identifiable(out, &indent, def)?;
            write_struct_serializable(out, &indent, def, meta)?;
            write_struct_deserializable(out, &indent, def, meta)?;
        }

        if !ns.is_empty() {
            writeln!(out, "    }}")?;
        }
    }

    writeln!(out, "}}")
}

fn write_functions_mod<W: Write>(
    defs: &[Definition],
    config: &Config,
    meta: &Metadata,
    out: &mut W,
) -> io::Result<()> {
    writeln!(out, "// @generated: do not edit by hand")?;
    writeln!(out, "pub mod functions {{")?;

    let grouped = grouper::group_by_ns(defs, Category::Functions);
    let mut namespaces: Vec<&String> = grouped.keys().collect();
    namespaces.sort();

    for ns in namespaces {
        let bucket = &grouped[ns];
        let indent: String = if ns.is_empty() {
            "    ".to_owned()
        } else {
            writeln!(out, "    pub mod {ns} {{")?;
            "        ".to_owned()
        };

        for def in bucket {
            write_struct(out, &indent, def, meta, config)?;
            write_identifiable(out, &indent, def)?;
            write_struct_serializable(out, &indent, def, meta)?;
            if config.deserializable_functions {
                write_struct_deserializable(out, &indent, def, meta)?;
            }
            write_remote_call(out, &indent, def, meta)?;
        }

        if !ns.is_empty() {
            writeln!(out, "    }}")?;
        }
    }

    writeln!(out, "}}")
}

// Struct pieces

fn generic_list(def: &Definition, bounds: &str) -> String {
    let mut params: Vec<&str> = Vec::new();
    for p in &def.params {
        if let ParameterType::Normal { ty, .. } = &p.ty
            && ty.generic_ref
            && !params.contains(&ty.name.as_str())
        {
            params.push(&ty.name);
        }
    }
    if params.is_empty() {
        String::new()
    } else {
        format!("<{}>", params.join(&format!("{bounds}, ")) + bounds)
    }
}

fn write_struct<W: Write>(
    out: &mut W,
    indent: &str,
    def: &Definition,
    meta: &Metadata,
    config: &Config,
) -> io::Result<()> {
    let kind = match def.category {
        Category::Types => "constructor",
        Category::Functions => "method",
    };
    writeln!(
        out,
        "\n{indent}/// [`{name}`](https://core.telegram.org/{kind}/{name})\n\
         {indent}///\n\
         {indent}/// Generated from:\n\
         {indent}/// ```tl\n\
         {indent}/// {def}\n\
         {indent}/// ```",
        name = def.full_name(),
    )?;

    if config.impl_debug {
        writeln!(out, "{indent}#[derive(Debug)]")?;
    }
    if config.impl_serde {
        writeln!(
            out,
            "{indent}#[derive(serde::Serialize, serde::Deserialize)]"
        )?;
    }
    writeln!(out, "{indent}#[derive(Clone, PartialEq)]")?;
    writeln!(
        out,
        "{indent}pub struct {}{} {{",
        n::def_type_name(def),
        generic_list(def, ""),
    )?;

    for param in &def.params {
        match &param.ty {
            ParameterType::Flags => {} // computed on-the-fly
            ParameterType::Normal { .. } => {
                writeln!(
                    out,
                    "{indent}    pub {}: {},",
                    n::param_attr_name(param),
                    n::param_qual_name(param, meta),
                )?;
            }
        }
    }
    writeln!(out, "{indent}}}")
}

fn write_identifiable<W: Write>(out: &mut W, indent: &str, def: &Definition) -> io::Result<()> {
    let gl = generic_list(def, "");
    writeln!(
        out,
        "{indent}impl{gl} crate::Identifiable for {}{gl} {{\n\
         {indent}    const CONSTRUCTOR_ID: u32 = {:#010x};\n\
         {indent}}}",
        n::def_type_name(def),
        def.id,
    )
}

fn write_struct_serializable<W: Write>(
    out: &mut W,
    indent: &str,
    def: &Definition,
    meta: &Metadata,
) -> io::Result<()> {
    let gl_decl = generic_list(def, ": crate::Serializable");
    let gl_use = generic_list(def, "");

    writeln!(
        out,
        "{indent}impl{gl_decl} crate::Serializable for {}{gl_use} {{",
        n::def_type_name(def)
    )?;

    let underscore = if def.category == Category::Types && def.params.is_empty() {
        "_"
    } else {
        ""
    };
    writeln!(
        out,
        "{indent}    fn serialize(&self, {underscore}buf: &mut impl Extend<u8>) {{"
    )?;

    if def.category == Category::Functions {
        writeln!(out, "{indent}        use crate::Identifiable;")?;
        writeln!(out, "{indent}        Self::CONSTRUCTOR_ID.serialize(buf);")?;
    }

    for param in &def.params {
        write_param_serialization(out, indent, def, meta, param)?;
    }

    writeln!(out, "{indent}    }}")?;
    writeln!(out, "{indent}}}")
}

fn write_param_serialization<W: Write>(
    out: &mut W,
    indent: &str,
    def: &Definition,
    meta: &Metadata,
    param: &ferogram_tl_parser::tl::Parameter,
) -> io::Result<()> {
    use ParameterType::*;

    match &param.ty {
        Flags => {
            if meta.is_unused_flag(def, param) {
                writeln!(out, "{indent}        0u32.serialize(buf);")?;
                return Ok(());
            }
            // Compute the flags bitmask from optional params
            write!(out, "{indent}        (")?;
            let mut first = true;
            for other in &def.params {
                if let Normal {
                    flag: Some(fl), ty, ..
                } = &other.ty
                {
                    if fl.name != param.name {
                        continue;
                    }
                    if !first {
                        write!(out, " | ")?;
                    }
                    first = false;
                    if ty.name == "true" {
                        write!(
                            out,
                            "if self.{} {{ 1 << {} }} else {{ 0 }}",
                            n::param_attr_name(other),
                            fl.index
                        )?;
                    } else {
                        write!(
                            out,
                            "if self.{}.is_some() {{ 1 << {} }} else {{ 0 }}",
                            n::param_attr_name(other),
                            fl.index
                        )?;
                    }
                }
            }
            if first {
                write!(out, "0u32")?;
            }
            writeln!(out, ").serialize(buf);")?;
        }
        Normal { ty, flag } => {
            let attr = n::param_attr_name(param);
            if flag.is_some() {
                if ty.name == "true" {
                    // bool flag: nothing to serialize, it's in the flags word
                } else {
                    writeln!(
                        out,
                        "{indent}        if let Some(v) = &self.{attr} {{ v.serialize(buf); }}"
                    )?;
                }
            } else {
                writeln!(out, "{indent}        self.{attr}.serialize(buf);")?;
            }
        }
    }
    Ok(())
}

fn write_struct_deserializable<W: Write>(
    out: &mut W,
    indent: &str,
    def: &Definition,
    meta: &Metadata,
) -> io::Result<()> {
    let gl_decl = generic_list(def, ": crate::Deserializable");
    let gl_use = generic_list(def, "");

    // Empty structs never read from `buf`. Name it `_buf` to suppress the
    // unused-variable warning in the generated output.
    let buf_name = if def.params.is_empty() { "_buf" } else { "buf" };

    writeln!(
        out,
        "{indent}impl{gl_decl} crate::Deserializable for {}{gl_use} {{",
        n::def_type_name(def)
    )?;
    writeln!(
        out,
        "{indent}    fn deserialize({buf_name}: crate::deserialize::Buffer) -> crate::deserialize::Result<Self> {{"
    )?;

    // Debug: entry banner (only for non-empty structs; empty ones use _buf)
    let struct_name = n::def_type_name(def);
    if !def.params.is_empty() {
        writeln!(
            out,
            "{indent}        if crate::deserialize::tl_debug() {{ \
             eprintln!(\"[TL] >>  {}::deserialize  pos={{}}\", buf.pos()); }}",
            struct_name
        )?;
    }

    // Deserialize params in exact TL schema order.
    // Flags fields are read inline where they appear - never hoisted.
    for param in &def.params {
        match &param.ty {
            ParameterType::Flags => {
                let fp_attr = n::param_attr_name(param);
                writeln!(
                    out,
                    "{indent}        if crate::deserialize::tl_debug() {{ \
                     eprintln!(\"[TL]   {struct_name}.{fp_attr} (flags) pos={{}}\", buf.pos()); }}"
                )?;
                writeln!(
                    out,
                    "{indent}        let _{fp_attr} = u32::deserialize(buf)?;"
                )?;
                writeln!(
                    out,
                    "{indent}        if crate::deserialize::tl_debug() {{ \
                     eprintln!(\"[TL]   {struct_name}.{fp_attr} = {{:#034b}}  pos={{}}\", _{fp_attr}, buf.pos()); }}"
                )?;
            }
            ParameterType::Normal { ty, flag } => {
                let attr = n::param_attr_name(param);
                // before
                writeln!(
                    out,
                    "{indent}        if crate::deserialize::tl_debug() {{ \
                     eprintln!(\"[TL]   {struct_name}.{attr} pos={{}}\", buf.pos()); }}"
                )?;
                if let Some(fl) = flag {
                    if ty.name == "true" {
                        writeln!(
                            out,
                            "{indent}        let {attr} = (_{} & (1 << {})) != 0;",
                            fl.name, fl.index
                        )?;
                    } else {
                        writeln!(
                            out,
                            "{indent}        let {attr} = if (_{} & (1 << {})) != 0 {{ Some({}::deserialize(buf)?) }} else {{ None }};",
                            fl.name,
                            fl.index,
                            n::type_item_path(ty, meta)
                        )?;
                    }
                } else {
                    writeln!(
                        out,
                        "{indent}        let {attr} = {}::deserialize(buf)?;",
                        n::type_item_path(ty, meta)
                    )?;
                }
                // after
                writeln!(
                    out,
                    "{indent}        if crate::deserialize::tl_debug() {{ \
                     eprintln!(\"[TL]   {struct_name}.{attr} done  pos={{}}\", buf.pos()); }}"
                )?;
            }
        }
    }

    // Debug: exit banner (only for non-empty structs; empty ones use _buf)
    if !def.params.is_empty() {
        writeln!(
            out,
            "{indent}        if crate::deserialize::tl_debug() {{ \
             eprintln!(\"[TL] <<  {struct_name}::deserialize done  pos={{}}\", buf.pos()); }}"
        )?;
    }

    writeln!(out, "{indent}        Ok(Self {{")?;
    for param in &def.params {
        if param.ty != ParameterType::Flags {
            let attr = n::param_attr_name(param);
            writeln!(out, "{indent}            {attr},")?;
        }
    }
    writeln!(out, "{indent}        }})")?;
    writeln!(out, "{indent}    }}")?;
    writeln!(out, "{indent}}}")
}

fn write_remote_call<W: Write>(
    out: &mut W,
    indent: &str,
    def: &Definition,
    meta: &Metadata,
) -> io::Result<()> {
    // Generic functions (e.g. invokeWithLayer<X>) need the type parameter on
    // the impl header and on the struct name, just like every other write_* helper.
    let gl_decl = generic_list(def, ": crate::Serializable + crate::Deserializable");
    let gl_use = generic_list(def, "");
    writeln!(
        out,
        "{indent}impl{gl_decl} crate::RemoteCall for {}{gl_use} {{",
        n::def_type_name(def)
    )?;
    writeln!(
        out,
        "{indent}    type Return = {};",
        n::type_qual_name(&def.ty, meta)
    )?;
    writeln!(out, "{indent}}}")
}

// Enum generation

fn write_enums_mod<W: Write>(
    defs: &[Definition],
    config: &Config,
    meta: &Metadata,
    out: &mut W,
) -> io::Result<()> {
    writeln!(out, "// @generated: do not edit by hand")?;
    writeln!(out, "pub mod enums {{")?;

    let grouped = grouper::group_types_by_ns(defs);
    let mut keys: Vec<&Option<String>> = grouped.keys().collect();
    keys.sort();

    for key in keys {
        let types = &grouped[key];
        let indent = if let Some(ns) = key {
            writeln!(out, "    pub mod {ns} {{")?;
            "        ".to_owned()
        } else {
            "    ".to_owned()
        };

        for ty in types.iter().filter(|t| !is_builtin(&t.name)) {
            write_enum(out, &indent, ty, meta, config)?;
            write_enum_serializable(out, &indent, ty, meta)?;
            write_enum_deserializable(out, &indent, ty, meta)?;
            if config.impl_from_type {
                write_impl_from(out, &indent, ty, meta)?;
            }
            if config.impl_from_enum {
                write_impl_try_from(out, &indent, ty, meta)?;
            }
        }

        if key.is_some() {
            writeln!(out, "    }}")?;
        }
    }

    writeln!(out, "}}")
}

fn write_enum<W: Write>(
    out: &mut W,
    indent: &str,
    ty: &ferogram_tl_parser::tl::Type,
    meta: &Metadata,
    config: &Config,
) -> io::Result<()> {
    writeln!(
        out,
        "\n{indent}/// [`{name}`](https://core.telegram.org/type/{name})",
        name = n::type_name(ty)
    )?;
    if config.impl_debug {
        writeln!(out, "{indent}#[derive(Debug)]")?;
    }
    if config.impl_serde {
        writeln!(
            out,
            "{indent}#[derive(serde::Serialize, serde::Deserialize)]"
        )?;
    }
    writeln!(out, "{indent}#[derive(Clone, PartialEq)]")?;
    writeln!(out, "{indent}pub enum {} {{", n::type_name(ty))?;

    for def in meta.defs_for_type(ty) {
        let variant = n::def_variant_name(def);
        if def.params.is_empty() {
            writeln!(out, "{indent}    {variant},")?;
        } else if meta.is_recursive(def) {
            writeln!(
                out,
                "{indent}    {variant}(Box<{}>),",
                n::def_qual_name(def)
            )?;
        } else {
            writeln!(out, "{indent}    {variant}({}),", n::def_qual_name(def))?;
        }
    }

    writeln!(out, "{indent}}}")
}

fn write_enum_serializable<W: Write>(
    out: &mut W,
    indent: &str,
    ty: &ferogram_tl_parser::tl::Type,
    meta: &Metadata,
) -> io::Result<()> {
    writeln!(
        out,
        "{indent}impl crate::Serializable for {} {{",
        n::type_name(ty)
    )?;
    writeln!(
        out,
        "{indent}    fn serialize(&self, buf: &mut impl Extend<u8>) {{"
    )?;
    writeln!(out, "{indent}        use crate::Identifiable;")?;
    writeln!(out, "{indent}        match self {{")?;

    for def in meta.defs_for_type(ty) {
        let variant = n::def_variant_name(def);
        let bind = if def.params.is_empty() { "" } else { "(x)" };
        writeln!(out, "{indent}            Self::{variant}{bind} => {{")?;
        writeln!(
            out,
            "{indent}                {}::CONSTRUCTOR_ID.serialize(buf);",
            n::def_qual_name(def)
        )?;
        if !def.params.is_empty() {
            writeln!(out, "{indent}                x.serialize(buf);")?;
        }
        writeln!(out, "{indent}            }}")?;
    }

    writeln!(out, "{indent}        }}")?;
    writeln!(out, "{indent}    }}")?;
    writeln!(out, "{indent}}}")
}

fn write_enum_deserializable<W: Write>(
    out: &mut W,
    indent: &str,
    ty: &ferogram_tl_parser::tl::Type,
    meta: &Metadata,
) -> io::Result<()> {
    writeln!(
        out,
        "{indent}impl crate::Deserializable for {} {{",
        n::type_name(ty)
    )?;
    writeln!(
        out,
        "{indent}    fn deserialize(buf: crate::deserialize::Buffer) -> crate::deserialize::Result<Self> {{"
    )?;
    let enum_name = n::type_name(ty);
    writeln!(out, "{indent}        use crate::Identifiable;")?;
    writeln!(out, "{indent}        let id = u32::deserialize(buf)?;")?;
    writeln!(
        out,
        "{indent}        if crate::deserialize::tl_debug() {{ \
         eprintln!(\"[TL] ENUM  {enum_name}  ctor={{:#010x}}  pos={{}}\", id, buf.pos()); }}"
    )?;
    writeln!(out, "{indent}        Ok(match id {{")?;

    for def in meta.defs_for_type(ty) {
        let variant = n::def_variant_name(def);
        let qual = n::def_qual_name(def);
        if def.params.is_empty() {
            writeln!(
                out,
                "{indent}            {qual}::CONSTRUCTOR_ID => Self::{variant},"
            )?;
        } else if meta.is_recursive(def) {
            writeln!(
                out,
                "{indent}            {qual}::CONSTRUCTOR_ID => Self::{variant}(Box::new({qual}::deserialize(buf)?)),"
            )?;
        } else {
            writeln!(
                out,
                "{indent}            {qual}::CONSTRUCTOR_ID => Self::{variant}({qual}::deserialize(buf)?),"
            )?;
        }
    }

    writeln!(
        out,
        "{indent}            _ => return Err(crate::deserialize::Error::UnexpectedConstructor {{ id }}),"
    )?;
    writeln!(out, "{indent}        }})")?;
    writeln!(out, "{indent}    }}")?;
    writeln!(out, "{indent}}}")
}

fn write_impl_from<W: Write>(
    out: &mut W,
    indent: &str,
    ty: &ferogram_tl_parser::tl::Type,
    meta: &Metadata,
) -> io::Result<()> {
    for def in meta.defs_for_type(ty) {
        let enum_name = n::type_name(ty);
        let qual = n::def_qual_name(def);
        let variant = n::def_variant_name(def);

        writeln!(out, "{indent}impl From<{qual}> for {enum_name} {{")?;
        let underscore = if def.params.is_empty() { "_" } else { "" };
        writeln!(out, "{indent}    fn from({underscore}x: {qual}) -> Self {{")?;
        if def.params.is_empty() {
            writeln!(out, "{indent}        Self::{variant}")?;
        } else if meta.is_recursive(def) {
            writeln!(out, "{indent}        Self::{variant}(Box::new(x))")?;
        } else {
            writeln!(out, "{indent}        Self::{variant}(x)")?;
        }
        writeln!(out, "{indent}    }}")?;
        writeln!(out, "{indent}}}")?;
    }
    Ok(())
}

fn write_impl_try_from<W: Write>(
    out: &mut W,
    indent: &str,
    ty: &ferogram_tl_parser::tl::Type,
    meta: &Metadata,
) -> io::Result<()> {
    let enum_name = n::type_name(ty);
    for def in meta.defs_for_type(ty) {
        if def.params.is_empty() {
            continue;
        }
        let qual = n::def_qual_name(def);
        let variant = n::def_variant_name(def);

        writeln!(out, "{indent}impl TryFrom<{enum_name}> for {qual} {{")?;
        writeln!(out, "{indent}    type Error = {enum_name};")?;
        writeln!(out, "{indent}    #[allow(unreachable_patterns)]")?;
        writeln!(
            out,
            "{indent}    fn try_from(v: {enum_name}) -> Result<Self, Self::Error> {{"
        )?;
        writeln!(out, "{indent}        match v {{")?;
        if meta.is_recursive(def) {
            writeln!(
                out,
                "{indent}            {enum_name}::{variant}(x) => Ok(*x),"
            )?;
        } else {
            writeln!(
                out,
                "{indent}            {enum_name}::{variant}(x) => Ok(x),"
            )?;
        }
        writeln!(out, "{indent}            other => Err(other),")?;
        writeln!(out, "{indent}        }}")?;
        writeln!(out, "{indent}    }}")?;
        writeln!(out, "{indent}}}")?;
    }
    Ok(())
}