phenotyper 0.3.0

Core compiler library for the Phenotyper structural artifact definition language
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
// SPDX-License-Identifier: Apache-2.0
//! Rust code emission from the validated IR.
//!
//! Produces idiomatic Rust source code implementing:
//! - Singular structs (REQ-CODEGEN-002)
//! - Plural wrapper structs (REQ-CODEGEN-003)
//! - Builder structs (REQ-CODEGEN-004)
//! - BuildError enum (REQ-CODEGEN-005)
//! - Render trait + implementations (REQ-CODEGEN-006)
//! - Union enums (REQ-CODEGEN-007)
//! - Namespace enums (REQ-CODEGEN-008)

use crate::ir::{
    EnumType, FieldDef, PhenotypeModule, PhenotypeType, RenderNode, SeparatorExpr, TypeAlias,
    ValueType,
};
use crate::symbol::{Cardinality, PrimitiveType, Requiredness};

use super::naming;

/// Emit the complete Rust module from a `PhenotypeModule`.
pub fn emit_module(module: &PhenotypeModule) -> String {
    let mut out = String::new();

    // Module header
    out.push_str("// This file is @generated by phenotyper. Do not edit.\n");
    out.push_str("#![allow(dead_code, unused_imports)]\n\n");

    // Render trait definition (REQ-CODEGEN-006)
    emit_render_trait(&mut out);

    // BuildError enum (REQ-CODEGEN-005)
    emit_build_error(&mut out);

    // Namespace enums (REQ-CODEGEN-008)
    for enum_type in &module.enums {
        emit_enum_type(enum_type, &mut out);
    }

    // Type aliases (union types at namespace level)
    for alias in &module.aliases {
        emit_type_alias(alias, module, &mut out);
    }

    // Phenotype types
    for pt in &module.types {
        emit_phenotype_type(pt, module, &mut out);
    }

    out
}

// ─── Render trait ───────────────────────────────────────────────────────────

fn emit_render_trait(out: &mut String) {
    out.push_str(
        "/// Trait for rendering phenotype instances to string output.\n\
         pub trait Render {\n\
         \x20\x20\x20\x20/// Render this instance into the provided buffer.\n\
         \x20\x20\x20\x20fn render_into(&self, out: &mut String);\n\
         \n\
         \x20\x20\x20\x20/// Render this instance to a new `String`.\n\
         \x20\x20\x20\x20fn render(&self) -> String {\n\
         \x20\x20\x20\x20\x20\x20\x20\x20let mut buf = String::new();\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self.render_into(&mut buf);\n\
         \x20\x20\x20\x20\x20\x20\x20\x20buf\n\
         \x20\x20\x20\x20}\n\
         }\n\n",
    );
}

// ─── BuildError ─────────────────────────────────────────────────────────────

fn emit_build_error(out: &mut String) {
    out.push_str(
        "/// Error type for builder validation.\n\
         #[derive(Debug)]\n\
         pub enum BuildError {\n\
         \x20\x20\x20\x20/// A required field was not set.\n\
         \x20\x20\x20\x20MissingField(&'static str),\n\
         \x20\x20\x20\x20/// A `OneOrMore` collection was empty.\n\
         \x20\x20\x20\x20CardinalityViolation(&'static str),\n\
         }\n\n\
         impl std::fmt::Display for BuildError {\n\
         \x20\x20\x20\x20fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {\n\
         \x20\x20\x20\x20\x20\x20\x20\x20match self {\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20BuildError::MissingField(name) => write!(f, \"missing required field: {}\", name),\n\
         \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20BuildError::CardinalityViolation(name) => write!(f, \"collection must not be empty: {}\", name),\n\
         \x20\x20\x20\x20\x20\x20\x20\x20}\n\
         \x20\x20\x20\x20}\n\
         }\n\n\
         impl std::error::Error for BuildError {}\n\n",
    );
}

// ─── Enum types ─────────────────────────────────────────────────────────────

fn emit_enum_type(enum_type: &EnumType, out: &mut String) {
    let rust_name = naming::to_rust_type_name(&enum_type.name);

    out.push_str(&format!(
        "#[derive(Debug, Clone, PartialEq, Eq)]\npub enum {rust_name} {{\n"
    ));
    for member in &enum_type.members {
        let variant = naming::to_rust_variant_name(member);
        out.push_str(&format!("    {variant},\n"));
    }
    out.push_str("}\n\n");

    // Render impl — emit the original declared spelling
    out.push_str(&format!("impl Render for {rust_name} {{\n"));
    out.push_str("    fn render_into(&self, out: &mut String) {\n");
    out.push_str("        match self {\n");
    for member in &enum_type.members {
        let variant = naming::to_rust_variant_name(member);
        out.push_str(&format!(
            "            {rust_name}::{variant} => out.push_str(\"{member}\"),\n"
        ));
    }
    out.push_str("        }\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");
}

// ─── Type aliases (union types) ─────────────────────────────────────────────

fn emit_type_alias(alias: &TypeAlias, module: &PhenotypeModule, out: &mut String) {
    let rust_name = naming::to_rust_type_name(&alias.name);

    match &alias.target {
        ValueType::Union(members) => {
            // Generate enum for union alias
            out.push_str(&format!(
                "#[derive(Debug, Clone, PartialEq)]\npub enum {rust_name} {{\n"
            ));
            for member in members {
                let (variant, ty) = union_variant_info(member);
                out.push_str(&format!("    {variant}({ty}),\n"));
            }
            out.push_str("}\n\n");

            // Render impl
            out.push_str(&format!("impl Render for {rust_name} {{\n"));
            out.push_str("    fn render_into(&self, out: &mut String) {\n");
            out.push_str("        match self {\n");
            for member in members {
                let (variant, _) = union_variant_info(member);
                let render_expr = union_variant_render(member);
                out.push_str(&format!(
                    "            {rust_name}::{variant}(val) => {render_expr},\n"
                ));
            }
            out.push_str("        }\n");
            out.push_str("    }\n");
            out.push_str("}\n\n");
        }
        other => {
            // Simple type alias
            let ty = rust_type(other, Cardinality::One, module);
            out.push_str(&format!("pub type {rust_name} = {ty};\n\n"));
        }
    }
}

// ─── Phenotype type ─────────────────────────────────────────────────────────

fn emit_phenotype_type(pt: &PhenotypeType, module: &PhenotypeModule, out: &mut String) {
    let rust_name = naming::to_rust_type_name(&pt.singular_name);

    // Union enums for union-typed fields (REQ-CODEGEN-007)
    for field in &pt.fields {
        if let ValueType::Union(members) = &field.ty {
            let enum_name = naming::to_union_enum_name(&pt.singular_name, &field.name);
            emit_field_union_enum(&enum_name, members, out);
        }
    }

    // Singular struct (REQ-CODEGEN-002)
    emit_singular_struct(pt, module, out);

    // Builder (REQ-CODEGEN-004)
    emit_builder(pt, module, out);

    // Render impl (REQ-CODEGEN-006)
    emit_render_impl(pt, module, out);

    // Plural wrapper (REQ-CODEGEN-003)
    if let Some(ref plural_name) = pt.plural_name {
        emit_plural_wrapper(&rust_name, plural_name, pt, module, out);
    }
}

// ─── Singular struct ────────────────────────────────────────────────────────

fn emit_singular_struct(pt: &PhenotypeType, module: &PhenotypeModule, out: &mut String) {
    let rust_name = naming::to_rust_type_name(&pt.singular_name);

    out.push_str(&format!(
        "#[derive(Debug, Clone)]\npub struct {rust_name} {{\n"
    ));
    for field in &pt.fields {
        let field_name = naming::to_rust_field_name(&field.name);
        let ty = field_rust_type(field, &pt.singular_name, module);
        out.push_str(&format!("    pub {field_name}: {ty},\n"));
    }
    out.push_str("}\n\n");

    // `builder()` convenience method
    let builder_name = naming::to_builder_name(&pt.singular_name);
    out.push_str(&format!("impl {rust_name} {{\n"));
    out.push_str(&format!(
        "    pub fn builder() -> {builder_name} {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20{builder_name}::new()\n\
         \x20\x20\x20\x20}}\n"
    ));
    out.push_str("}\n\n");
}

// ─── Builder ────────────────────────────────────────────────────────────────

fn emit_builder(pt: &PhenotypeType, module: &PhenotypeModule, out: &mut String) {
    let rust_name = naming::to_rust_type_name(&pt.singular_name);
    let builder_name = naming::to_builder_name(&pt.singular_name);

    // Builder struct: all fields are Option<T> or Vec<T>
    out.push_str(&format!(
        "#[derive(Debug, Default)]\npub struct {builder_name} {{\n"
    ));
    for field in &pt.fields {
        let field_name = naming::to_rust_field_name(&field.name);
        let ty = builder_field_type(field, &pt.singular_name, module);
        out.push_str(&format!("    {field_name}: {ty},\n"));
    }
    out.push_str("}\n\n");

    // Builder impl
    out.push_str(&format!("impl {builder_name} {{\n"));

    // new()
    out.push_str(
        "    pub fn new() -> Self {\n\
         \x20\x20\x20\x20\x20\x20\x20\x20Self::default()\n\
         \x20\x20\x20\x20}\n\n",
    );

    // Setters for each field
    for field in &pt.fields {
        let field_name = naming::to_rust_field_name(&field.name);
        let val_ty = field_rust_type_bare(field, &pt.singular_name, module);
        if is_collection_field(field) {
            // Collection fields get a setter that replaces the vec
            out.push_str(&format!(
                "    pub fn {field_name}(&mut self, val: {val_ty}) -> &mut Self {{\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20self.{field_name} = val;\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20self\n\
                 \x20\x20\x20\x20}}\n\n"
            ));
        } else {
            out.push_str(&format!(
                "    pub fn {field_name}(&mut self, val: {val_ty}) -> &mut Self {{\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20self.{field_name} = Some(val);\n\
                 \x20\x20\x20\x20\x20\x20\x20\x20self\n\
                 \x20\x20\x20\x20}}\n\n"
            ));
        }
    }

    // build()
    out.push_str(&format!(
        "    pub fn build(self) -> Result<{rust_name}, BuildError> {{\n"
    ));
    for field in &pt.fields {
        let field_name = naming::to_rust_field_name(&field.name);
        if is_collection_field(field) {
            // Cardinality check for OneOrMore
            if field.cardinality == Cardinality::OneOrMore {
                out.push_str(&format!(
                    "        if self.{field_name}.is_empty() {{\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\x20\
                     return Err(BuildError::CardinalityViolation(\"{field_name}\"));\n\
                     \x20\x20\x20\x20\x20\x20\x20\x20}}\n"
                ));
            }
        } else if field.requiredness == Requiredness::Required {
            out.push_str(&format!(
                "        let {field_name} = self.{field_name}\
                 .ok_or(BuildError::MissingField(\"{field_name}\"))?;\n"
            ));
        }
    }

    out.push_str(&format!("        Ok({rust_name} {{\n"));
    for field in &pt.fields {
        let field_name = naming::to_rust_field_name(&field.name);
        if is_collection_field(field) || field.requiredness == Requiredness::Optional {
            out.push_str(&format!("            {field_name}: self.{field_name},\n"));
        } else {
            out.push_str(&format!("            {field_name},\n"));
        }
    }
    out.push_str("        })\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");
}

// ─── Render impl ────────────────────────────────────────────────────────────

fn emit_render_impl(pt: &PhenotypeType, module: &PhenotypeModule, out: &mut String) {
    let rust_name = naming::to_rust_type_name(&pt.singular_name);

    if let Some(ref parent_name) = pt.parent_context {
        // This nested type references parent fields → generate render_with_parent
        let parent_rust = naming::to_rust_type_name(parent_name);

        // Standard Render trait impl that delegates to render_with_parent
        // (panics at runtime if called without parent — this is a compile-time
        // contract enforced by the DSL, not the generated Rust code)
        out.push_str(&format!("impl Render for {rust_name} {{\n"));
        out.push_str("    fn render_into(&self, _out: &mut String) {\n");
        out.push_str(&format!(
            "        panic!(\"{rust_name}::render_into called without parent; \
             use render_with_parent instead\");\n"
        ));
        out.push_str("    }\n");
        out.push_str("}\n\n");

        // render_with_parent method
        out.push_str(&format!("impl {rust_name} {{\n"));
        out.push_str(&format!(
            "    pub fn render_with_parent(&self, parent: &{parent_rust}, out: &mut String) {{\n"
        ));
        for node in &pt.render {
            emit_render_node(node, pt, module, out, "        ");
        }
        out.push_str("    }\n");
        out.push_str("}\n\n");
    } else {
        // Standard render_into
        out.push_str(&format!("impl Render for {rust_name} {{\n"));
        out.push_str("    fn render_into(&self, out: &mut String) {\n");
        for node in &pt.render {
            emit_render_node(node, pt, module, out, "        ");
        }
        out.push_str("    }\n");
        out.push_str("}\n\n");
    }
}

fn emit_render_node(
    node: &RenderNode,
    pt: &PhenotypeType,
    module: &PhenotypeModule,
    out: &mut String,
    indent: &str,
) {
    match node {
        RenderNode::Text(text) => {
            let escaped = text.replace('\\', "\\\\").replace('"', "\\\"");
            out.push_str(&format!("{indent}out.push_str(\"{escaped}\");\n"));
        }

        RenderNode::Emit(field_id) => {
            if let Some(field) = pt.fields.iter().find(|f| f.id == *field_id) {
                let field_name = naming::to_rust_field_name(&field.name);
                emit_field_render(&field_name, &field.ty, module, out, indent);
            }
        }

        RenderNode::ParentFieldRef {
            parent_type: _,
            field_name,
        } => {
            let rust_field = naming::to_rust_field_name(field_name);
            out.push_str(&format!("{indent}out.push_str(&parent.{rust_field});\\n"));
        }

        RenderNode::Eol { field } => {
            if let Some(field_id) = field {
                if let Some(f) = pt.fields.iter().find(|f| f.id == *field_id) {
                    let field_name = naming::to_rust_field_name(&f.name);
                    out.push_str(&format!("{indent}out.push_str(&self.{field_name});\n"));
                }
            } else {
                out.push_str(&format!("{indent}out.push('\\n');\n"));
            }
        }

        RenderNode::Join { field, separator } => {
            if let Some(f) = pt.fields.iter().find(|f| f.id == *field) {
                let field_name = naming::to_rust_field_name(&f.name);
                let sep_expr = match separator {
                    SeparatorExpr::Literal(s) => {
                        let escaped = s.replace('\\', "\\\\").replace('"', "\\\"");
                        format!("\"{escaped}\"")
                    }
                    SeparatorExpr::Field(sep_id) => {
                        if let Some(sf) = pt.fields.iter().find(|f| f.id == *sep_id) {
                            let sep_name = naming::to_rust_field_name(&sf.name);
                            format!("&self.{sep_name}")
                        } else {
                            "\"\"".to_string()
                        }
                    }
                };

                let iter_expr = format!("self.{field_name}.iter()");

                out.push_str(&format!("{indent}let mut first = true;\n"));
                out.push_str(&format!("{indent}for item in {iter_expr} {{\n"));
                out.push_str(&format!("{indent}    if !first {{\n"));
                out.push_str(&format!("{indent}        out.push_str({sep_expr});\n"));
                out.push_str(&format!("{indent}    }}\n"));
                out.push_str(&format!("{indent}    first = false;\n"));

                // Render the item
                if let ValueType::Imported(imp) = &f.ty {
                    // UFCS through the exporter's Render trait (see emit_field_render).
                    let prefix = naming::imported_module_prefix(&module.namespace, &imp.namespace);
                    out.push_str(&format!(
                        "{indent}    {prefix}Render::render_into(item, out);\n"
                    ));
                } else if needs_render_into(&f.ty) {
                    out.push_str(&format!("{indent}    item.render_into(out);\n"));
                } else {
                    emit_item_render("item", &f.ty, out, &format!("{indent}    "));
                }

                out.push_str(&format!("{indent}}}\n"));
            }
        }

        RenderNode::IfSet { field, body } => {
            if let Some(f) = pt.fields.iter().find(|f| f.id == *field) {
                let field_name = naming::to_rust_field_name(&f.name);
                out.push_str(&format!(
                    "{indent}if let Some(ref val) = self.{field_name} {{\n"
                ));
                // Inside the block, render body. Emit references need to
                // use `val` instead of `self.field_name`
                for child in body {
                    emit_guarded_render_node(
                        child,
                        pt,
                        module,
                        *field,
                        out,
                        &format!("{indent}    "),
                    );
                }
                out.push_str(&format!("{indent}}}\n"));
            }
        }

        RenderNode::IfNotEmpty { field, body } => {
            if let Some(f) = pt.fields.iter().find(|f| f.id == *field) {
                let field_name = naming::to_rust_field_name(&f.name);
                let is_plural = matches!(f.ty, ValueType::UserPlural { .. });
                let check = if is_plural {
                    format!("!self.{field_name}.as_slice().is_empty()")
                } else {
                    format!("!self.{field_name}.is_empty()")
                };
                out.push_str(&format!("{indent}if {check} {{\n"));
                for child in body {
                    emit_render_node(child, pt, module, out, &format!("{indent}    "));
                }
                out.push_str(&format!("{indent}}}\n"));
            }
        }
    }
}

/// Emit a render node inside an @ifset guard, where the guarded field's
/// reference is through `val` rather than `self.field_name`.
fn emit_guarded_render_node(
    node: &RenderNode,
    pt: &PhenotypeType,
    module: &PhenotypeModule,
    guarded_field_id: crate::symbol::FieldId,
    out: &mut String,
    indent: &str,
) {
    match node {
        RenderNode::Emit(field_id) if *field_id == guarded_field_id => {
            // This is the guarded field — use `val` from the if-let binding
            if let Some(field) = pt.fields.iter().find(|f| f.id == *field_id) {
                emit_val_render("val", &field.ty, module, out, indent);
            }
        }
        // For all other nodes, delegate to the standard renderer
        other => emit_render_node(other, pt, module, out, indent),
    }
}

// ─── Plural wrapper ─────────────────────────────────────────────────────────

fn emit_plural_wrapper(
    singular_rust_name: &str,
    plural_name: &str,
    pt: &PhenotypeType,
    module: &PhenotypeModule,
    out: &mut String,
) {
    let plural_rust_name = naming::to_rust_type_name(plural_name);
    let builder_name = naming::to_builder_name(plural_name);

    // Struct (with Default derive for builder compatibility)
    out.push_str(&format!(
        "#[derive(Debug, Clone, Default)]\npub struct {plural_rust_name} {{\n\
         \x20\x20\x20\x20items: Vec<{singular_rust_name}>,\n\
         }}\n\n"
    ));

    // Core methods (REQ-CODEGEN-003)
    out.push_str(&format!("impl {plural_rust_name} {{\n"));
    out.push_str(
        "    pub fn new() -> Self {\n\
         \x20\x20\x20\x20\x20\x20\x20\x20Self { items: Vec::new() }\n\
         \x20\x20\x20\x20}\n\n",
    );
    out.push_str(&format!(
        "    pub fn from_vec(items: Vec<{singular_rust_name}>) -> Self {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20Self {{ items }}\n\
         \x20\x20\x20\x20}}\n\n"
    ));
    out.push_str(&format!(
        "    pub fn into_vec(self) -> Vec<{singular_rust_name}> {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self.items\n\
         \x20\x20\x20\x20}}\n\n"
    ));
    out.push_str(&format!(
        "    pub fn as_slice(&self) -> &[{singular_rust_name}] {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20&self.items\n\
         \x20\x20\x20\x20}}\n\n"
    ));
    out.push_str(&format!(
        "    pub fn iter(&self) -> std::slice::Iter<'_, {singular_rust_name}> {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self.items.iter()\n\
         \x20\x20\x20\x20}}\n\n"
    ));
    out.push_str(&format!(
        "    pub fn builder() -> {builder_name} {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20{builder_name}::new()\n\
         \x20\x20\x20\x20}}\n"
    ));
    out.push_str("}\n\n");

    // From<Vec<T>>
    out.push_str(&format!(
        "impl From<Vec<{singular_rust_name}>> for {plural_rust_name} {{\n\
         \x20\x20\x20\x20fn from(items: Vec<{singular_rust_name}>) -> Self {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20Self {{ items }}\n\
         \x20\x20\x20\x20}}\n\
         }}\n\n"
    ));

    // Into<Vec<T>> (via From)
    out.push_str(&format!(
        "impl From<{plural_rust_name}> for Vec<{singular_rust_name}> {{\n\
         \x20\x20\x20\x20fn from(wrapper: {plural_rust_name}) -> Self {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20wrapper.items\n\
         \x20\x20\x20\x20}}\n\
         }}\n\n"
    ));

    // Plural builder (REQ-CODEGEN-004)
    out.push_str(&format!(
        "#[derive(Debug, Default)]\npub struct {builder_name} {{\n\
         \x20\x20\x20\x20items: Vec<{singular_rust_name}>,\n\
         }}\n\n"
    ));
    out.push_str(&format!("impl {builder_name} {{\n"));
    out.push_str(
        "    pub fn new() -> Self {\n\
         \x20\x20\x20\x20\x20\x20\x20\x20Self::default()\n\
         \x20\x20\x20\x20}\n\n",
    );
    out.push_str(&format!(
        "    pub fn push(&mut self, item: {singular_rust_name}) -> &mut Self {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self.items.push(item);\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self\n\
         \x20\x20\x20\x20}}\n\n"
    ));
    out.push_str(&format!(
        "    pub fn extend(&mut self, items: impl IntoIterator<Item = {singular_rust_name}>) -> &mut Self {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self.items.extend(items);\n\
         \x20\x20\x20\x20\x20\x20\x20\x20self\n\
         \x20\x20\x20\x20}}\n\n"
    ));
    out.push_str(&format!(
        "    pub fn build(self) -> Result<{plural_rust_name}, BuildError> {{\n\
         \x20\x20\x20\x20\x20\x20\x20\x20Ok({plural_rust_name} {{ items: self.items }})\n\
         \x20\x20\x20\x20}}\n"
    ));
    out.push_str("}\n\n");

    // Render impl for plural — uses the phenotype's join semantics
    emit_plural_render(&plural_rust_name, pt, module, out);
}

fn emit_plural_render(
    plural_rust_name: &str,
    pt: &PhenotypeType,
    _module: &PhenotypeModule,
    out: &mut String,
) {
    out.push_str(&format!("impl Render for {plural_rust_name} {{\n"));
    out.push_str("    fn render_into(&self, out: &mut String) {\n");
    out.push_str("        let mut first = true;\n");
    out.push_str("        for item in self.items.iter() {\n");
    out.push_str("            if !first {\n");

    // Find separator from render nodes (look for Join)
    let sep = find_join_separator_literal(pt);
    out.push_str(&format!("                out.push_str(\"{sep}\");\n"));

    out.push_str("            }\n");
    out.push_str("            first = false;\n");
    out.push_str("            item.render_into(out);\n");
    out.push_str("        }\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");
}

// ─── Field union enums ──────────────────────────────────────────────────────

fn emit_field_union_enum(enum_name: &str, members: &[ValueType], out: &mut String) {
    out.push_str(&format!(
        "#[derive(Debug, Clone, PartialEq)]\npub enum {enum_name} {{\n"
    ));
    for member in members {
        let (variant, ty) = union_variant_info(member);
        out.push_str(&format!("    {variant}({ty}),\n"));
    }
    out.push_str("}\n\n");

    // Render impl
    out.push_str(&format!("impl Render for {enum_name} {{\n"));
    out.push_str("    fn render_into(&self, out: &mut String) {\n");
    out.push_str("        match self {\n");
    for member in members {
        let (variant, _) = union_variant_info(member);
        let render_call = union_variant_render(member);
        out.push_str(&format!(
            "            {enum_name}::{variant}(val) => {render_call},\n"
        ));
    }
    out.push_str("        }\n");
    out.push_str("    }\n");
    out.push_str("}\n\n");
}

// ─── Helpers ────────────────────────────────────────────────────────────────

/// Map a `ValueType` + cardinality to a Rust type string.
fn rust_type(ty: &ValueType, cardinality: Cardinality, module: &PhenotypeModule) -> String {
    let base = match ty {
        ValueType::Primitive(p) => primitive_rust_type(*p).to_string(),
        ValueType::UserSingular(id) => format!("/* TypeId({}) */", id.0),
        ValueType::UserPlural { .. } => "/* plural */".to_string(),
        ValueType::Enum(id) => format!("/* EnumId({}) */", id.0),
        ValueType::TypeAlias(id) => format!("/* AliasId({}) */", id.0),
        ValueType::Imported(imp) => imported_type_path(imp, module),
        ValueType::Union(_) => "/* union */".to_string(),
    };

    match cardinality {
        Cardinality::One => base,
        Cardinality::OneOrMore | Cardinality::ZeroOrMore => format!("Vec<{base}>"),
    }
}

/// Get the full Rust type for a field, accounting for requiredness and cardinality.
fn field_rust_type(field: &FieldDef, parent_type_name: &str, module: &PhenotypeModule) -> String {
    let base = field_rust_type_bare(field, parent_type_name, module);
    if field.requiredness == Requiredness::Optional && !is_collection_field(field) {
        format!("Option<{base}>")
    } else {
        base
    }
}

/// Get the bare Rust type for a field (no Option wrapping).
fn field_rust_type_bare(
    field: &FieldDef,
    parent_type_name: &str,
    module: &PhenotypeModule,
) -> String {
    match &field.ty {
        ValueType::Primitive(p) => {
            let base = primitive_rust_type(*p).to_string();
            match field.cardinality {
                Cardinality::One => base,
                _ => format!("Vec<{base}>"),
            }
        }
        ValueType::UserSingular(id) => resolve_type_name(*id, module),
        ValueType::UserPlural { collection_of } => {
            // Find the plural name via the singular type's plural_name
            if let Some(pt) = module.types.iter().find(|t| t.id == *collection_of) {
                if let Some(ref pn) = pt.plural_name {
                    naming::to_rust_type_name(pn)
                } else {
                    format!("Vec<{}>", naming::to_rust_type_name(&pt.singular_name))
                }
            } else {
                "Vec<()>".to_string()
            }
        }
        ValueType::Enum(id) => {
            if let Some(e) = module.enums.iter().find(|e| e.id == *id) {
                naming::to_rust_type_name(&e.name)
            } else {
                "()".to_string()
            }
        }
        ValueType::TypeAlias(id) => {
            if let Some(a) = module.aliases.iter().find(|a| a.id == *id) {
                naming::to_rust_type_name(&a.name)
            } else {
                "()".to_string()
            }
        }
        ValueType::Imported(imp) => imported_type_path(imp, module),
        ValueType::Union(_) => naming::to_union_enum_name(parent_type_name, &field.name),
    }
}

/// The Rust path of an imported declaration, relative to this module.
fn imported_type_path(imp: &crate::ir::ImportedRef, module: &PhenotypeModule) -> String {
    format!(
        "{}{}",
        naming::imported_module_prefix(&module.namespace, &imp.namespace),
        naming::to_rust_type_name(&imp.name)
    )
}

/// Resolve a TypeId to its Rust type name.
fn resolve_type_name(id: crate::symbol::TypeId, module: &PhenotypeModule) -> String {
    if let Some(pt) = module.types.iter().find(|t| t.id == id) {
        naming::to_rust_type_name(&pt.singular_name)
    } else {
        format!("UnknownType{}", id.0)
    }
}

/// Get the builder's storage type for a field.
fn builder_field_type(
    field: &FieldDef,
    parent_type_name: &str,
    module: &PhenotypeModule,
) -> String {
    let bare = field_rust_type_bare(field, parent_type_name, module);
    if is_collection_field(field) {
        bare // Already a Vec
    } else {
        format!("Option<{bare}>")
    }
}

fn is_collection_field(field: &FieldDef) -> bool {
    field.cardinality != Cardinality::One || matches!(field.ty, ValueType::UserPlural { .. })
}

fn primitive_rust_type(p: PrimitiveType) -> &'static str {
    match p {
        PrimitiveType::String => "String",
        PrimitiveType::Int64 => "i64",
        PrimitiveType::Real64 => "f64",
        PrimitiveType::Bool => "bool",
        PrimitiveType::Date => "String",
        PrimitiveType::Time => "String",
        PrimitiveType::DateTime => "String",
    }
}

/// Get union variant info: (variant_name, rust_type)
fn union_variant_info(ty: &ValueType) -> (String, String) {
    match ty {
        ValueType::Primitive(p) => {
            let variant = match p {
                PrimitiveType::String => "String",
                PrimitiveType::Int64 => "Int64",
                PrimitiveType::Real64 => "Real64",
                PrimitiveType::Bool => "Bool",
                PrimitiveType::Date => "Date",
                PrimitiveType::Time => "Time",
                PrimitiveType::DateTime => "DateTime",
            };
            (variant.to_string(), primitive_rust_type(*p).to_string())
        }
        ValueType::UserSingular(id) => (format!("Type{}", id.0), format!("/* TypeId({}) */", id.0)),
        _ => ("Unknown".to_string(), "()".to_string()),
    }
}

/// Get the render call for a union variant value.
fn union_variant_render(ty: &ValueType) -> String {
    match ty {
        ValueType::Primitive(PrimitiveType::String) => "out.push_str(val)".to_string(),
        ValueType::Primitive(PrimitiveType::Int64) => "out.push_str(&val.to_string())".to_string(),
        ValueType::Primitive(PrimitiveType::Real64) => "out.push_str(&val.to_string())".to_string(),
        ValueType::Primitive(PrimitiveType::Bool) => {
            "out.push_str(if *val { \"true\" } else { \"false\" })".to_string()
        }
        ValueType::Primitive(_) => "out.push_str(val)".to_string(),
        ValueType::UserSingular(_) => "val.render_into(out)".to_string(),
        _ => "()".to_string(),
    }
}

/// Emit code to render a field by name.
fn emit_field_render(
    field_name: &str,
    ty: &ValueType,
    module: &PhenotypeModule,
    out: &mut String,
    indent: &str,
) {
    match ty {
        ValueType::Primitive(PrimitiveType::String) => {
            out.push_str(&format!("{indent}out.push_str(&self.{field_name});\n"));
        }
        ValueType::Primitive(PrimitiveType::Int64 | PrimitiveType::Real64) => {
            out.push_str(&format!(
                "{indent}out.push_str(&self.{field_name}.to_string());\n"
            ));
        }
        ValueType::Primitive(PrimitiveType::Bool) => {
            out.push_str(&format!(
                "{indent}out.push_str(if self.{field_name} {{ \"true\" }} else {{ \"false\" }});\n"
            ));
        }
        ValueType::Primitive(_) => {
            // Date/Time/DateTime are stored as String
            out.push_str(&format!("{indent}out.push_str(&self.{field_name});\n"));
        }
        ValueType::Imported(imp) => {
            // The imported type implements the *exporter's* `Render` trait
            // (every generated module defines its own), so call it UFCS —
            // no trait import needed in this module.
            let prefix = naming::imported_module_prefix(&module.namespace, &imp.namespace);
            out.push_str(&format!(
                "{indent}{prefix}Render::render_into(&self.{field_name}, out);\n"
            ));
        }
        _ => {
            // Local user types, enums, unions: use render_into
            out.push_str(&format!("{indent}self.{field_name}.render_into(out);\n"));
        }
    }
}

/// Emit code to render a `val` binding (inside @ifset).
fn emit_val_render(
    var_name: &str,
    ty: &ValueType,
    module: &PhenotypeModule,
    out: &mut String,
    indent: &str,
) {
    match ty {
        ValueType::Primitive(PrimitiveType::String) => {
            out.push_str(&format!("{indent}out.push_str({var_name});\n"));
        }
        ValueType::Primitive(PrimitiveType::Int64 | PrimitiveType::Real64) => {
            out.push_str(&format!("{indent}out.push_str(&{var_name}.to_string());\n"));
        }
        ValueType::Primitive(PrimitiveType::Bool) => {
            out.push_str(&format!(
                "{indent}out.push_str(if *{var_name} {{ \"true\" }} else {{ \"false\" }});\n"
            ));
        }
        ValueType::Primitive(_) => {
            out.push_str(&format!("{indent}out.push_str({var_name});\n"));
        }
        ValueType::Imported(imp) => {
            // UFCS through the exporter's Render trait (see emit_field_render).
            let prefix = naming::imported_module_prefix(&module.namespace, &imp.namespace);
            out.push_str(&format!(
                "{indent}{prefix}Render::render_into({var_name}, out);\n"
            ));
        }
        _ => {
            out.push_str(&format!("{indent}{var_name}.render_into(out);\n"));
        }
    }
}

/// Emit code to render an `item` variable in a join loop.
fn emit_item_render(var_name: &str, ty: &ValueType, out: &mut String, indent: &str) {
    match ty {
        ValueType::Primitive(PrimitiveType::String) => {
            out.push_str(&format!("{indent}out.push_str({var_name});\n"));
        }
        ValueType::Primitive(PrimitiveType::Int64 | PrimitiveType::Real64) => {
            out.push_str(&format!("{indent}out.push_str(&{var_name}.to_string());\n"));
        }
        _ => {
            out.push_str(&format!("{indent}{var_name}.render_into(out);\n"));
        }
    }
}

/// Whether a value type needs `.render_into()` (vs direct string ops).
fn needs_render_into(ty: &ValueType) -> bool {
    !matches!(
        ty,
        ValueType::Primitive(PrimitiveType::String)
            | ValueType::Primitive(PrimitiveType::Int64)
            | ValueType::Primitive(PrimitiveType::Real64)
    )
}

/// Find the separator literal from a type's render nodes (for plural wrapper render).
fn find_join_separator_literal(pt: &PhenotypeType) -> String {
    for node in &pt.render {
        if let RenderNode::Join { separator, .. } = node {
            match separator {
                SeparatorExpr::Literal(s) => {
                    return s.replace('\\', "\\\\").replace('"', "\\\"");
                }
                SeparatorExpr::Field(_) => {
                    // For field-based separators, the plural wrapper can't
                    // know the separator at compile time — use empty default
                    return String::new();
                }
            }
        }
    }
    String::new()
}