alef 0.83.2

Opinionated polyglot binding generator for Rust libraries
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
use crate::backends::rustler::template_env;
use crate::codegen::cfg::is_host_owned_rust_path;
use crate::codegen::conversions::{VariantDeclaration, enum_variant_declaration};
use crate::codegen::doc_emission::doc_first_paragraph_joined;
use crate::codegen::shared::binding_fields;
use crate::core::config::ResolvedCrateConfig;
use crate::core::hash::{self, CommentStyle};
use crate::core::ir::{EnumVariant, TypeDef, TypeRef};
use ahash::{AHashMap, AHashSet};
use heck::ToSnakeCase;
use std::collections::{HashMap, HashSet};

use super::context::emit_elixir_doc_attr;
use super::json_values::{
    elixir_field_default, elixir_field_name_with_type, elixir_safe_atom, elixir_safe_attr_name, elixir_safe_param_name,
    elixir_safe_type_name, elixir_struct_field_typespec, elixir_typespec, elixir_variant_atom,
};

/// Generate a `defmodule {AppModule}.{TypeName}` file with a `defstruct` for a non-opaque type.
pub(in crate::backends::rustler::gen_bindings) fn gen_elixir_struct_module(
    typ: &TypeDef,
    app_module: &str,
    enum_defaults: &HashMap<String, String>,
    opaque_types: &AHashSet<String>,
    known_struct_types: &AHashSet<String>,
) -> String {
    let mut out = String::with_capacity(512);

    out.push_str(&hash::header(CommentStyle::Hash));

    let ctx = minijinja::context! {
        app_module => app_module,
        type_name => &typ.name,
    };
    out.push_str(&template_env::render("struct_module_header.jinja", ctx));
    if !typ.doc.is_empty() {
        emit_elixir_doc_attr(&mut out, "moduledoc", &typ.doc, "  ");
    } else {
        out.push_str("  @moduledoc false\n");
    }
    out.push('\n');

    let default_types: AHashSet<String> = enum_defaults.keys().cloned().collect();
    if !typ.doc.is_empty() {
        let first_para = doc_first_paragraph_joined(&typ.doc);
        emit_elixir_doc_attr(&mut out, "typedoc", &first_para, "  ");
    }
    out.push_str("  @type t :: %__MODULE__{\n");

    let fields: Vec<_> = binding_fields(&typ.fields).collect();
    if !fields.is_empty() {
        for (i, field) in fields.iter().enumerate() {
            let field_name = field.name.to_snake_case();
            let field_type =
                elixir_struct_field_typespec(&field.ty, app_module, opaque_types, &default_types, known_struct_types);
            let field_defaults_to_nil = matches!(
                field.ty,
                TypeRef::String | TypeRef::Char | TypeRef::Path | TypeRef::Json
            );
            let field_type_with_optional =
                if (field.optional || field_defaults_to_nil) && !matches!(field.ty, TypeRef::Optional(_)) {
                    format!("{field_type} | nil")
                } else {
                    field_type
                };

            out.push_str(&template_env::render(
                "elixir_struct_type_field.ex.jinja",
                minijinja::context! {
                    field_name => &field_name,
                    field_type => &field_type_with_optional,
                    is_last => i == fields.len() - 1,
                },
            ));
        }
    }
    out.push_str("        }\n\n");

    if fields.is_empty() {
        out.push_str(&template_env::render("struct_empty.jinja", minijinja::context! {}));
    } else {
        out.push_str("  defstruct ");
        for (i, field) in fields.iter().enumerate() {
            let default = elixir_field_default(field, &field.ty, enum_defaults, opaque_types);
            let name = field.name.to_snake_case();
            if i == 0 {
                out.push_str(&template_env::render(
                    "elixir_enum_field_first.jinja",
                    minijinja::context! {
                        name => &name,
                        default => &default,
                    },
                ));
            } else {
                out.push_str(&template_env::render(
                    "elixir_enum_field_rest.jinja",
                    minijinja::context! {
                        name => &name,
                        default => &default,
                    },
                ));
            }
        }
        out.push('\n');
    }

    if typ.has_default {
        out.push('\n');
        out.push_str("  defimpl Jason.Encoder do\n");
        out.push_str("    @doc false\n");
        out.push_str("    def encode(value, opts) do\n");
        out.push_str("      value\n");
        out.push_str("      |> Map.from_struct()\n");
        out.push_str("      |> Enum.reject(fn {_k, v} -> v == nil end)\n");
        out.push_str("      |> Enum.into(%{})\n");
        out.push_str("      |> Jason.Encoder.encode(opts)\n");
        out.push_str("    end\n");
        out.push_str("  end\n");
    }

    if typ.name == "HeaderMetadata" {
        out.push('\n');
        out.push_str("  @doc \"Validate that the header level is within valid range (1-6).\"\n");
        out.push_str("  @spec valid?(t()) :: boolean()\n");
        out.push_str("  def valid?(%__MODULE__{level: level}) do\n");
        out.push_str("    level >= 1 and level <= 6\n");
        out.push_str("  end\n");
    }

    while out.ends_with("\n\n") {
        out.pop();
    }
    out.push_str(&template_env::render(
        "struct_module_footer.jinja",
        minijinja::context! {},
    ));
    out
}

/// Generate an idiomatic Elixir wrapper module for an opaque type.
///
/// The native NIF returns the opaque type as a Rustler resource (passed as
/// `reference()` to Elixir). This wrapper wraps the reference in a struct
/// (`%SampleLanguagePack.Parser{ref: ...}`) and exposes the type's
/// methods as functions that delegate to the corresponding NIF
/// (`{type_lower}_{method_name}`) provided by `{AppModule}.Native`.
///
/// Async methods delegate to the `_async` NIF variant (see
/// `gen_bindings/functions.rs`). Methods that map to a `Streaming` adapter
/// emit a `Stream.unfold/2`-based wrapper that drives the underlying
/// `_start`/`_next` NIF pair instead of attempting a sync call.
#[cfg(test)]
pub(in crate::backends::rustler::gen_bindings) fn gen_elixir_opaque_module(
    typ: &TypeDef,
    app_module: &str,
    config: &ResolvedCrateConfig,
) -> String {
    gen_elixir_opaque_module_with_types(typ, app_module, config, &AHashSet::new(), &AHashSet::new())
}

pub(in crate::backends::rustler::gen_bindings) fn gen_elixir_opaque_module_with_types(
    typ: &TypeDef,
    app_module: &str,
    config: &ResolvedCrateConfig,
    opaque_types: &AHashSet<String>,
    default_types: &AHashSet<String>,
) -> String {
    let mut out = String::with_capacity(512);

    out.push_str(&hash::header(CommentStyle::Hash));

    let ctx = minijinja::context! {
        app_module => app_module,
        type_name => &typ.name,
    };
    out.push_str(&template_env::render("struct_module_header.jinja", ctx));
    if !typ.doc.is_empty() {
        emit_elixir_doc_attr(&mut out, "moduledoc", &typ.doc, "  ");
    } else {
        out.push_str("  @moduledoc false\n");
    }
    out.push('\n');

    let needs_native_alias = typ.has_default || !typ.methods.is_empty() || typ.is_variant_wrapper;
    if needs_native_alias {
        out.push_str(&template_env::render(
            "elixir_native_alias.ex.jinja",
            minijinja::context! {
                app_module => app_module,
            },
        ));
    }
    out.push_str("  defstruct [:ref]\n\n");
    if !typ.doc.is_empty() {
        let first_para = doc_first_paragraph_joined(&typ.doc);
        emit_elixir_doc_attr(&mut out, "typedoc", &first_para, "  ");
    }
    out.push_str("  @type t :: %__MODULE__{ref: reference()}\n\n");

    let type_lower = typ.name.to_lowercase();

    let streaming_method_names: AHashSet<String> = config
        .adapters
        .iter()
        .filter(|a| matches!(a.pattern, crate::core::config::AdapterPattern::Streaming))
        .filter(|a| a.owner_type.as_deref() == Some(typ.name.as_str()))
        .map(|a| a.name.clone())
        .collect();

    if typ.has_default {
        out.push_str(&template_env::render(
            "elixir_opaque_new.ex.jinja",
            minijinja::context! {
                type_lower => &type_lower,
            },
        ));
    }

    for method in &typ.methods {
        let method_name = method.name.to_snake_case();

        if typ.has_default && method.name == "new" && method.receiver.is_none() {
            continue;
        }

        if typ.has_default && method.name == "default" && method.receiver.is_none() {
            continue;
        }

        if streaming_method_names.contains(&method.name) {
            let start_fn = format!("{type_lower}_{}_start", method.name);
            let next_fn = format!("{type_lower}_{}_next", method.name);

            let mut def_args: Vec<String> = Vec::new();
            let mut start_call_args: Vec<String> = Vec::new();
            if method.receiver.is_some() {
                def_args.push("obj".to_string());
                start_call_args.push("obj.ref".to_string());
            }
            let json_encode_params = crate::backends::rustler::gen_bindings::public_api_args::json_encode_param_indices(
                &method.params,
                opaque_types,
                default_types,
            );
            let tagged_enum_params = AHashMap::new();
            for (index, p) in method.params.iter().enumerate() {
                let safe = elixir_safe_param_name(&p.name);
                def_args.push(safe.clone());
                start_call_args.push(crate::backends::rustler::gen_bindings::public_api_args::nif_arg(
                    index,
                    &safe,
                    &json_encode_params,
                    &tagged_enum_params,
                ));
            }

            let doc_first = method.doc.lines().next().unwrap_or("").replace('"', "\\\"");
            out.push_str(&template_env::render(
                "elixir_opaque_stream_method.ex.jinja",
                minijinja::context! {
                    doc_first => &doc_first,
                    method_name => &method_name,
                    def_args => &def_args.join(", "),
                    start_fn => &start_fn,
                    start_call_args => &start_call_args.join(", "),
                    next_fn => &next_fn,
                },
            ));
            out.push('\n');
            continue;
        }

        let nif_fn = if method.is_async {
            if method.name.ends_with("_async") {
                format!("{type_lower}_{}", method.name)
            } else {
                format!("{type_lower}_{}_async", method.name)
            }
        } else {
            format!("{type_lower}_{}", method.name)
        };

        let mut call_args: Vec<String> = Vec::new();
        let mut def_args: Vec<String> = Vec::new();
        if method.receiver.is_some() {
            def_args.push("obj".to_string());
            call_args.push("obj.ref".to_string());
        }
        let json_encode_params = crate::backends::rustler::gen_bindings::public_api_args::json_encode_param_indices(
            &method.params,
            opaque_types,
            default_types,
        );
        let tagged_enum_params = AHashMap::new();
        for (index, p) in method.params.iter().enumerate() {
            let safe = elixir_safe_param_name(&p.name);
            def_args.push(safe.clone());
            call_args.push(crate::backends::rustler::gen_bindings::public_api_args::nif_arg(
                index,
                &safe,
                &json_encode_params,
                &tagged_enum_params,
            ));
        }

        let doc_first = method.doc.lines().next().unwrap_or("").replace('"', "\\\"");

        // Any method that returns Self — whether a receiver-based chainable
        // builder method (`&mut self -> Self`) or a static alternate
        // constructor — must re-wrap the returned NIF ref in
        // `%__MODULE__{ref: ...}`. Without this, receiver-based builder
        // methods silently degrade the struct to a bare `reference()` after
        // the first chained call (the NIF returns a raw ref, not a struct). ~keep
        let returns_self = matches!(&method.return_type, TypeRef::Named(n) if n == &typ.name);
        let unwrap_deserialization_result =
            crate::backends::rustler::gen_bindings::public_api_args::method_deserialization_introduces_result(
                method,
                true,
                opaque_types,
                default_types,
            );

        if !doc_first.is_empty() && !out.is_empty() && !out.ends_with("\n\n") {
            out.push('\n');
        }

        out.push_str(&template_env::render(
            "elixir_opaque_method_wrapper.ex.jinja",
            minijinja::context! {
                doc_first => &doc_first,
                method_name => &method_name,
                def_args => &def_args.join(", "),
                returns_self => returns_self,
                unwrap_result => unwrap_deserialization_result,
                preserve_result => method.is_async || method.error_type.is_some(),
                nif_fn => &nif_fn,
                call_args => &call_args.join(", "),
            },
        ));
        out.push('\n');
    }

    if typ.has_default {
        out.push_str(&template_env::render(
            "elixir_opaque_default.ex.jinja",
            minijinja::context! {
                type_lower => &type_lower,
            },
        ));
    }

    while out.ends_with("\n\n") {
        out.pop();
    }
    out.push_str(&template_env::render(
        "struct_module_footer.jinja",
        minijinja::context! {},
    ));
    out
}

/// Generate a `defmodule {AppModule}.{EnumName}` file for an enum.
///
/// Simple enums (all variants have no fields) get a `@type t :: :variant1 | :variant2 | ...`
/// union type using snake_case atoms, mirroring the Rustler `NifUnitEnum` atom encoding.
///
/// Data enums (one or more variants have fields) get a module with per-variant type aliases
/// since Elixir has no single structural type for tagged union variants.
#[allow(dead_code)]
pub(in crate::backends::rustler::gen_bindings) fn gen_elixir_enum_module(
    enum_def: &crate::core::ir::EnumDef,
    app_module: &str,
) -> String {
    // No `core_import`/`configured_features` context here; `""` reads as host-owned (permissive,
    // per `is_host_owned_rust_path`'s own doc) and `None` reads as "unknown", so
    // `enum_variant_declaration` never drops anything -- this test-only wrapper is a pure
    // pass-through of every declared variant, matching its behavior before cfg filtering existed. ~keep
    gen_elixir_enum_module_with_known_types(enum_def, app_module, &AHashSet::new(), "", None)
}

/// Whether `enum_def`'s data variants all carry a single tuple field of a Named type -- the
/// exact gate `gen_rustler_flat_data_enum` (`gen_bindings/types.rs`) uses to choose a flat
/// `NifStruct` (one discriminator field + one optional field per variant) over a
/// `NifTaggedEnum` tuple. The Elixir-side `wire_value/1` dispatch (below) must agree with this
/// gate exactly, so both sides call this single function instead of keeping the condition in
/// sync by hand. ~keep
pub(in crate::backends::rustler::gen_bindings) fn is_flat_data_enum(enum_def: &crate::core::ir::EnumDef) -> bool {
    let has_data = enum_def.variants.iter().any(|v| !v.fields.is_empty());
    has_data
        && enum_def
            .variants
            .iter()
            .filter(|v| !v.fields.is_empty())
            .all(|v| v.is_tuple)
}

/// The discriminator field name a flat data enum carries when the source enum has no explicit
/// `#[serde(tag = "...")]`. `"type"` mirrors the fallback the wasm backend already uses for the
/// same concept (`src/backends/wasm/gen_bindings/enums.rs`) and serde's own `tag = "type"`
/// convention -- not a domain word borrowed from any one consumer crate.
///
/// Every emitter that names this field -- the Rust `NifStruct` field
/// (`gen_rustler_flat_data_enum` and its `From` impls in `gen_bindings/types.rs`), the Elixir
/// `@type` alias, and the Elixir `wire_value/1` map clause (both below) -- must call this
/// function instead of hard-coding the fallback independently, or the emitted sides can disagree
/// on the key like the `@type` alias and `wire_value/1` once did. ~keep
pub(in crate::backends::rustler::gen_bindings) fn flat_data_enum_discriminator(
    enum_def: &crate::core::ir::EnumDef,
) -> &str {
    crate::codegen::serde_enum_repr::tagged_object_tag_key(enum_def)
}

/// Escape a wire value for embedding in a double-quoted Elixir string literal.
///
/// Delegates to the backend's one escaping authority. The inline
/// `replace('\\', ..).replace('"', ..)` this replaced covered the two characters that break the
/// PARSE and neither of the two that do not: `#`, which makes the literal interpolate, and
/// control characters. ~keep
fn escape_elixir_string_literal(value: &str) -> String {
    crate::backends::rustler::elixir_escape::escape_elixir_string_literal(value)
}

/// `core_import`/`configured_features` decide which variants this Elixir-facing module
/// documents and exposes, via the same [`enum_variant_declaration`] authority
/// `gen_bindings::types::gen_enum` (this crate's own NIF declaration, `gen_bindings/types.rs`)
/// already consults: a FOREIGN cfg-gated variant this binding's own configured feature set
/// proves unreachable is dropped from the `@type`, the per-atom accessor, and the `wire_value/1`
/// dispatch alike -- never just documented as absent while still being reachable. Before this fix
/// this module always documented and exposed every variant regardless of `configured_features`
/// while the NIF declaration (once fixed) and the conversions already dropped the unreachable
/// ones: an Elixir caller could reference an atom the NIF layer can never actually produce or
/// accept. A host-owned cfg-gated variant is still always kept, matching every other backend's
/// declaration surface. ~keep
pub(in crate::backends::rustler::gen_bindings) fn gen_elixir_enum_module_with_known_types(
    enum_def: &crate::core::ir::EnumDef,
    app_module: &str,
    known_types: &AHashSet<String>,
    core_import: &str,
    configured_features: Option<&[String]>,
) -> String {
    let mut out = String::with_capacity(256);

    out.push_str(&hash::header(CommentStyle::Hash));

    let ctx = minijinja::context! {
        app_module => app_module,
        enum_name => &enum_def.name,
    };
    out.push_str(&template_env::render("enum_module_header.jinja", ctx));
    if !enum_def.doc.is_empty() {
        emit_elixir_doc_attr(&mut out, "moduledoc", &enum_def.doc, "  ");
    } else {
        out.push_str("  @moduledoc false\n");
    }
    out.push('\n');

    let is_host_enum = is_host_owned_rust_path(core_import, &enum_def.rust_path);
    let configured_features_set: Option<HashSet<&str>> =
        configured_features.map(|features| features.iter().map(String::as_str).collect());
    let declared_variants: Vec<&EnumVariant> = enum_def
        .variants
        .iter()
        .filter(|variant| {
            !matches!(
                enum_variant_declaration(variant, is_host_enum, configured_features_set.as_ref()),
                VariantDeclaration::Drop
            )
        })
        .collect();

    let is_simple = declared_variants.iter().all(|v| v.fields.is_empty());

    if is_simple {
        let atom_arms: Vec<String> = declared_variants
            .iter()
            .map(|v| format!(":{}", elixir_variant_atom(&v.name)))
            .collect();
        if !enum_def.doc.is_empty() {
            let first_para = doc_first_paragraph_joined(&enum_def.doc);
            emit_elixir_doc_attr(&mut out, "typedoc", &first_para, "  ");
        }
        let single_line = format!("  @type t :: {}", atom_arms.join(" | "));
        if single_line.len() <= 120 {
            out.push_str(&template_env::render(
                "elixir_enum_type_single_line.jinja",
                minijinja::context! {
                    arms => &atom_arms.join(" | "),
                },
            ));
        } else {
            out.push_str("  @type t ::\n");
            for (i, arm) in atom_arms.iter().enumerate() {
                if i == 0 {
                    out.push_str(&template_env::render(
                        "elixir_enum_type_arm_first.jinja",
                        minijinja::context! {
                            arm => arm,
                        },
                    ));
                } else {
                    out.push_str(&template_env::render(
                        "elixir_enum_type_arm_rest.jinja",
                        minijinja::context! {
                            arm => arm,
                        },
                    ));
                }
            }
        }
        out.push('\n');

        for variant in &declared_variants {
            let snake_name = crate::codegen::naming::pascal_to_snake(&variant.name);
            let safe_name = elixir_safe_param_name(&snake_name);
            let attr_name = elixir_safe_attr_name(&safe_name);
            let atom_literal = elixir_variant_atom(&variant.name);
            out.push_str(&template_env::render(
                "elixir_enum_attr.jinja",
                minijinja::context! {
                    attr_name => &attr_name,
                    atom_name => &atom_literal,
                },
            ));
        }
        out.push('\n');
        for variant in &declared_variants {
            let snake_name = crate::codegen::naming::pascal_to_snake(&variant.name);
            let safe_name = elixir_safe_param_name(&snake_name);
            let attr_name = elixir_safe_attr_name(&safe_name);
            if !variant.doc.is_empty() {
                let first_para = doc_first_paragraph_joined(&variant.doc);
                emit_elixir_doc_attr(&mut out, "doc", &first_para, "  ");
            }
            out.push_str(&template_env::render(
                "elixir_enum_accessor.jinja",
                minijinja::context! {
                    atom_name => &safe_name,
                    attr_name => &attr_name,
                },
            ));
        }

        out.push_str(&template_env::render(
            "elixir_enum_wire_value_header.jinja",
            minijinja::context! {},
        ));
        for variant in &declared_variants {
            // The runtime atom Rustler actually produces is always
            // `pascal_to_snake(variant.name)` -- serde_rename never influences it (serde and
            // rustler attributes are independent proc macros over the same variant; see
            // `emit_tagged_enum_encoder` in `public_api_args.rs`, which relies on the exact
            // same fact to build its Elixir-input-to-wire-JSON encoder). Matching a
            // serde_rename-derived atom here would leave a variant's true runtime atom with no
            // wire_value/1 clause, raising FunctionClauseError instead of returning the wire
            // string. ~keep
            let atom_literal = elixir_variant_atom(&variant.name);
            let wire = crate::codegen::naming::wire_variant_value(
                &variant.name,
                variant.serde_rename.as_deref(),
                enum_def.serde_rename_all.as_deref(),
            );
            out.push_str(&template_env::render(
                "elixir_enum_wire_value_atom_clause.jinja",
                minijinja::context! {
                    atom_literal => &atom_literal,
                    wire => &escape_elixir_string_literal(&wire),
                },
            ));
        }
    } else {
        if !enum_def.doc.is_empty() {
            let first_para = doc_first_paragraph_joined(&enum_def.doc);
            emit_elixir_doc_attr(&mut out, "typedoc", &first_para, "  ");
        }
        out.push_str("  @type t :: term()\n");
        out.push('\n');
        // The discriminator key documented in each variant's `@type` alias below must be the
        // exact same key `wire_value/1`'s map clause reads (see `flat_data_enum_discriminator`)
        // -- both are computed once, here, from the same function so the doc and the runtime
        // dispatch cannot disagree on the key name. ~keep
        let struct_type_discriminator = elixir_safe_atom(flat_data_enum_discriminator(enum_def));
        for variant in &declared_variants {
            let snake_name = crate::codegen::naming::pascal_to_snake(&variant.name);
            let variant_atom = format!(":{}", elixir_variant_atom(&variant.name));
            let type_name = elixir_safe_type_name(&elixir_safe_param_name(&snake_name));
            if !variant.doc.is_empty() {
                let first_para = doc_first_paragraph_joined(&variant.doc);
                emit_elixir_doc_attr(&mut out, "typedoc", &first_para, "  ");
            }
            if variant.fields.is_empty() {
                out.push_str(&template_env::render(
                    "elixir_data_enum_unit_type.jinja",
                    minijinja::context! {
                        type_name => &type_name,
                        variant_atom => &variant_atom,
                    },
                ));
            } else {
                let field_types: Vec<String> = variant
                    .fields
                    .iter()
                    .enumerate()
                    .map(|(idx, f)| {
                        let type_name = match &f.ty {
                            TypeRef::Named(n) => Some(n.as_str()),
                            TypeRef::String => Some("String"),
                            TypeRef::Bytes => Some("bytes"),
                            TypeRef::Char => Some("char"),
                            TypeRef::Path => Some("path"),
                            TypeRef::Json => Some("json"),
                            TypeRef::Primitive(p) => match p {
                                crate::core::ir::PrimitiveType::Bool => Some("bool"),
                                crate::core::ir::PrimitiveType::U8 => Some("u8"),
                                crate::core::ir::PrimitiveType::U16 => Some("u16"),
                                crate::core::ir::PrimitiveType::U32 => Some("u32"),
                                crate::core::ir::PrimitiveType::U64 => Some("u64"),
                                crate::core::ir::PrimitiveType::Usize => Some("usize"),
                                crate::core::ir::PrimitiveType::I8 => Some("i8"),
                                crate::core::ir::PrimitiveType::I16 => Some("i16"),
                                crate::core::ir::PrimitiveType::I32 => Some("i32"),
                                crate::core::ir::PrimitiveType::I64 => Some("i64"),
                                crate::core::ir::PrimitiveType::Isize => Some("isize"),
                                crate::core::ir::PrimitiveType::F32 => Some("f32"),
                                crate::core::ir::PrimitiveType::F64 => Some("f64"),
                            },
                            _ => None,
                        };

                        let field_name =
                            elixir_field_name_with_type(&f.name, idx, type_name, &variant.name, variant.fields.len());

                        let field_type = if let TypeRef::Named(n) = &f.ty {
                            if known_types.contains(n) {
                                format!("{app_module}.{}.t()", n)
                            } else {
                                let opaque_types = AHashSet::new();
                                let default_types = AHashSet::new();
                                elixir_typespec(&f.ty, &opaque_types, &default_types)
                            }
                        } else {
                            let opaque_types = AHashSet::new();
                            let default_types = AHashSet::new();
                            elixir_typespec(&f.ty, &opaque_types, &default_types)
                        };

                        format!("{field_name}: {field_type}")
                    })
                    .collect();
                out.push_str(&template_env::render(
                    "elixir_data_enum_struct_type.jinja",
                    minijinja::context! {
                        type_name => &type_name,
                        discriminator => &struct_type_discriminator,
                        variant_atom => &variant_atom,
                        field_types => field_types.join(", "),
                    },
                ));
            }
        }

        // `collect_all_variant_constructors` is a backend-agnostic helper with no cfg awareness
        // of its own (it filters only on shape: data-carrying, non-tuple, not
        // `binding_excluded`); restrict its output to the names `declared_variants` above
        // already resolved as present, so a dropped foreign cfg-gated variant does not get a
        // constructor function here either. ~keep
        let declared_variant_names: HashSet<&str> = declared_variants.iter().map(|v| v.name.as_str()).collect();
        let constructors: Vec<_> = crate::codegen::generators::collect_all_variant_constructors(enum_def)
            .into_iter()
            .filter(|ctor| declared_variant_names.contains(ctor.variant_name))
            .collect();
        if !constructors.is_empty() {
            out.push('\n');
            for ctor in &constructors {
                let atom = elixir_safe_atom(&ctor.snake_name);
                let fn_name = elixir_safe_param_name(&ctor.snake_name);
                let params: Vec<String> = ctor.params.iter().map(|p| elixir_safe_param_name(&p.name)).collect();
                let map_entries: Vec<String> = ctor
                    .params
                    .iter()
                    .zip(&params)
                    .map(|(p, param_name)| format!("{}: {param_name}", p.name))
                    .collect();
                out.push_str(&template_env::render(
                    "elixir_enum_variant_constructor.jinja",
                    minijinja::context! {
                        fn_name => &fn_name,
                        params => params.join(", "),
                        atom => &atom,
                        map_entries => map_entries.join(", "),
                    },
                ));
            }
        }

        // `wire_value/1` must dispatch on every runtime shape this enum can arrive in from
        // Rustler: a bare atom (a unit variant, or the discriminator of a `NifTaggedEnum`
        // tuple), a `{atom, ...}` tuple (`NifTaggedEnum`), or a map/struct with a discriminator
        // field (the flat `NifStruct` `is_flat_data_enum` emits) whose value is already the
        // exact `wire_variant_value` string -- see `flat_enum_from_core_variant_*.jinja`. The
        // atom clauses below cover the unit case AND the tuple case (the tuple clause recurses
        // into them via `elem(value, 0)`), so a single function works for both `NifTaggedEnum`
        // shapes without needing a separate branch here. ~keep
        out.push_str(&template_env::render(
            "elixir_enum_wire_value_header.jinja",
            minijinja::context! {},
        ));
        for variant in &declared_variants {
            // The runtime atom Rustler actually produces is always
            // `pascal_to_snake(variant.name)` -- serde_rename never influences it (serde and
            // rustler attributes are independent proc macros over the same variant; see
            // `emit_tagged_enum_encoder` in `public_api_args.rs`, which relies on the exact
            // same fact to build its Elixir-input-to-wire-JSON encoder). Matching a
            // serde_rename-derived atom here would leave a variant's true runtime atom with no
            // wire_value/1 clause, raising FunctionClauseError instead of returning the wire
            // string. ~keep
            let atom_literal = elixir_variant_atom(&variant.name);
            let wire = crate::codegen::naming::wire_variant_value(
                &variant.name,
                variant.serde_rename.as_deref(),
                enum_def.serde_rename_all.as_deref(),
            );
            out.push_str(&template_env::render(
                "elixir_enum_wire_value_atom_clause.jinja",
                minijinja::context! {
                    atom_literal => &atom_literal,
                    wire => &escape_elixir_string_literal(&wire),
                },
            ));
        }
        out.push_str(&template_env::render(
            "elixir_enum_wire_value_tuple_clause.jinja",
            minijinja::context! {},
        ));
        if is_flat_data_enum(enum_def) {
            let discriminator = elixir_safe_atom(flat_data_enum_discriminator(enum_def));
            out.push_str(&template_env::render(
                "elixir_enum_wire_value_map_clause.jinja",
                minijinja::context! {
                    discriminator => &discriminator,
                },
            ));

            // Only the flat-struct shape decodes to a real `%Module{}`/map term with a
            // `__struct__` key, so only it can dispatch a `String.Chars` protocol impl.
            // Atoms and tuples have no per-value dispatch target -- `wire_value/1` above is
            // the only mechanism that works for those shapes. ~keep
            out.push_str(&template_env::render(
                "elixir_enum_string_chars_impl.jinja",
                minijinja::context! {
                    app_module => app_module,
                    enum_name => &enum_def.name,
                },
            ));
        }
    }

    out.push_str(&template_env::render(
        "enum_module_footer.jinja",
        minijinja::context! {},
    ));
    out
}

#[cfg(test)]
mod enum_module_cfg_tests;