ferogram-tl-gen 0.6.5

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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
/*
 * Copyright (c) 2026 Ankit Chaubey <ankitchaubey.dev@gmail.com>
 * https://github.com/ankit-chaubey
 *
 * Project: ferogram
 * Website: https://ferogram.dev
 *
 * Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
 * https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
 * <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your option.
 * This file may not be copied, modified, or distributed except according
 * to those terms.
 */

use std::collections::HashMap;
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,
    /// Emit `.field()` accessors on enums whose variants share a field name
    /// and type (see `write_enum_accessors`).
    pub gen_field_accessors: 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,
            gen_field_accessors: true,
        }
    }
}

// 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 config.gen_field_accessors {
                write_enum_accessors(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(())
}

// Field accessor generation
//
// For an enum type with several constructors, look for parameter names that
// resolve to the same Rust type across variants and emit a `.field()`
// accessor. This is scoped narrowly on purpose:
//
// - A field name only qualifies if every variant that defines it agrees on
//   the exact Rust type. Any mismatch drops that field entirely, no partial
//   generation, no coercion.
// - If the field is present (optionally behind a flag) in every variant, the
//   accessor returns `&Ty` and the match is exhaustive.
// - If only a subset of variants carry it, the accessor returns `Option<&Ty>`
//   with a `_ => None` arm covering the rest.
// - Fields whose type touches a generic parameter are skipped, since the
//   accessor lives on the (non-generic) enum itself.
// - This does not attempt struct-like restructuring across mismatched shapes
//   (e.g. collapsing a `name`/`site_name` pair into one field) that stays
//   hand-written.

/// Per-field bookkeeping while scanning a type's constructors.
struct FieldAgg {
    /// Rust type once, `None` before the first sighting.
    rust_type: Option<String>,
    /// Set once two variants disagree on `rust_type`; excludes the field.
    mismatched: bool,
    /// One slot per constructor, in the same order as `defs_for_type`.
    /// `Some(is_flag_optional)` if that constructor carries the field.
    presence: Vec<Option<bool>>,
}

/// True if `ty` (or any nested generic argument) refers to a generic
/// parameter, meaning it can't be named from outside the constructor.
fn type_is_generic(ty: &ferogram_tl_parser::tl::Type) -> bool {
    ty.generic_ref
        || ty
            .generic_arg
            .as_deref()
            .map(type_is_generic)
            .unwrap_or(false)
}

fn write_enum_accessors<W: Write>(
    out: &mut W,
    indent: &str,
    ty: &ferogram_tl_parser::tl::Type,
    meta: &Metadata,
) -> io::Result<()> {
    let defs = meta.defs_for_type(ty);
    if defs.len() < 2 {
        return Ok(());
    }

    // Insertion-ordered field names so output stays stable across runs
    // (HashMap iteration order isn't).
    let mut order: Vec<String> = Vec::new();
    let mut fields: HashMap<String, FieldAgg> = HashMap::new();

    for (i, def) in defs.iter().enumerate() {
        for param in &def.params {
            let ParameterType::Normal { ty: pty, flag } = &param.ty else {
                continue;
            };
            if type_is_generic(pty) {
                continue;
            }

            let field = n::param_attr_name(param);
            let (rust_type, is_optional) = if flag.is_some() && pty.name == "true" {
                ("bool".to_owned(), false)
            } else {
                (n::type_qual_name(pty, meta), flag.is_some())
            };

            let agg = fields.entry(field.clone()).or_insert_with(|| {
                order.push(field.clone());
                FieldAgg {
                    rust_type: None,
                    mismatched: false,
                    presence: vec![None; defs.len()],
                }
            });

            match &agg.rust_type {
                None => agg.rust_type = Some(rust_type),
                Some(existing) if *existing != rust_type => agg.mismatched = true,
                _ => {}
            }
            agg.presence[i] = Some(is_optional);
        }
    }

    let mut emitted_header = false;

    for field in &order {
        let agg = &fields[field];
        if agg.mismatched {
            continue;
        }
        let Some(rust_type) = &agg.rust_type else {
            continue;
        };

        // Not worth a match statement over a single variant.
        let present_count = agg.presence.iter().filter(|p| p.is_some()).count();
        if present_count < 2 {
            continue;
        }

        let all_present = present_count == defs.len();
        let any_optional = agg.presence.iter().any(|p| matches!(p, Some(true)));
        // Guaranteed on every variant and never behind a flag: skip the
        // Option wrapper and the catch-all arm entirely.
        let direct = all_present && !any_optional;

        if !emitted_header {
            writeln!(out, "\n{indent}impl {} {{", n::type_name(ty))?;
            emitted_header = true;
        }

        let ret_ty = if direct {
            format!("&{rust_type}")
        } else {
            format!("Option<&{rust_type}>")
        };

        writeln!(
            out,
            "{indent}    /// Returns `{field}` if present in this variant."
        )?;
        writeln!(out, "{indent}    pub fn {field}(&self) -> {ret_ty} {{")?;
        writeln!(out, "{indent}        match self {{")?;

        for (i, def) in defs.iter().enumerate() {
            let variant = n::def_variant_name(def);
            let bind = if def.params.is_empty() { "" } else { "(x)" };

            match agg.presence[i] {
                Some(true) => writeln!(
                    out,
                    "{indent}            Self::{variant}{bind} => x.{field}.as_ref(),"
                )?,
                Some(false) => {
                    let expr = if direct {
                        format!("&x.{field}")
                    } else {
                        format!("Some(&x.{field})")
                    };
                    writeln!(out, "{indent}            Self::{variant}{bind} => {expr},")?
                }
                None => {} // covered by the wildcard arm below
            }
        }

        if !all_present {
            writeln!(out, "{indent}            _ => None,")?;
        }

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

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

    Ok(())
}