openapi-model-generator 0.6.3

A robust Rust library and CLI tool for generating type-safe Rust models from OpenAPI 3.0 specifications with advanced composition support
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
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
use std::sync::OnceLock;

use crate::{
    models::{
        CompositionModel, EnumModel, Model, ModelType, RequestModel, ResponseModel, TypeAliasModel,
        UnionModel, UnionType,
    },
    Result,
};
use indexmap::IndexMap;

bitflags::bitflags! {
    struct RequiredUses: u8 {
        const UUID = 0b00000001;
        const DATETIME = 0b00000010;
        const DATE = 0b00000100;
    }

    /// Choose what type of structs you want to generate:
    ///  - Models (generated always)
    ///  - Requests (optional)
    ///  - Responses (optional)
    pub struct GenerateMode: u8 {
        /// Models will be always include to output
        const MODELS = 0;
        /// Additional includes request structs to output
        const REQUESTS = 1 << 0;
        /// Additional includes response structs to output
        const RESPONSES = 1 << 1;
        /// Outputs all possible structs: models, request and response structs
        const ALL = Self::REQUESTS.bits() | Self::RESPONSES.bits();
    }
}

impl Default for GenerateMode {
    fn default() -> Self {
        Self::ALL
    }
}

static HDR: OnceLock<String> = OnceLock::new();

fn create_header() -> String {
    HDR.get_or_init(|| {
        format!(
            r#"
//!
//! Generated from an OAS specification by {}(v{})
//!

"#,
            option_env!("CARGO_PKG_NAME").unwrap_or("openapi-model-generator"),
            option_env!("CARGO_PKG_VERSION").unwrap_or("unknown")
        )
    })
    .clone()
}

const RUST_RESERVED_KEYWORDS: &[&str] = &[
    "as", "break", "const", "continue", "crate", "else", "enum", "extern", "false", "fn", "for",
    "if", "impl", "in", "let", "loop", "match", "mod", "move", "mut", "pub", "ref", "return",
    "self", "Self", "static", "struct", "super", "trait", "true", "type", "unsafe", "use", "where",
    "while", "abstract", "become", "box", "do", "final", "gen", "macro", "override", "priv", "try",
    "typeof", "unsized", "virtual", "yield",
];

const EMPTY_RESPONSE_NAME: &str = "UnknownResponse";
const EMPTY_REQUEST_NAME: &str = "UnknownRequest";

fn is_reserved_word(string_to_check: &str) -> bool {
    RUST_RESERVED_KEYWORDS.contains(&string_to_check.to_lowercase().as_str())
}

fn generate_description_docs(
    description: &Option<String>,
    fallback_str: &str,
    indent: &str,
) -> String {
    let mut output = String::new();
    if let Some(desc) = description {
        for line in desc.lines() {
            output.push_str(&format!("{}/// {}\n", indent, line.trim()));
        }
    } else if !fallback_str.is_empty() {
        output.push_str(&format!("{}/// {}\n", indent, fallback_str));
    }

    output
}

fn to_snake_case(name: &str) -> String {
    let cleaned: String = name
        .chars()
        .map(|c| if c.is_ascii_alphanumeric() { c } else { '_' })
        .collect();

    let mut snake = String::new();

    for (i, c) in cleaned.chars().enumerate() {
        if c.is_ascii_uppercase() {
            if i != 0 {
                snake.push('_');
            }
            snake.push(c.to_ascii_lowercase());
        } else {
            snake.push(c);
        }
    }
    snake = snake.replace("__", "_");

    if snake == "self" {
        snake.push('_');
    }

    if snake
        .chars()
        .next()
        .map(|c| c.is_ascii_digit())
        .unwrap_or(false)
    {
        snake = format!("_{snake}");
    }

    snake
}

/// Checks if custom attributes contain a derive attribute
fn has_custom_derive(custom_attrs: &Option<Vec<String>>) -> bool {
    if let Some(attrs) = custom_attrs {
        attrs
            .iter()
            .any(|attr| attr.trim().starts_with("#[derive("))
    } else {
        false
    }
}

/// Checks if custom attributes contain a serde attribute
fn has_custom_serde(custom_attrs: &Option<Vec<String>>) -> bool {
    if let Some(attrs) = custom_attrs {
        attrs.iter().any(|attr| attr.trim().starts_with("#[serde("))
    } else {
        false
    }
}

/// Generates a `impl std::fmt::Display` block for a named type, unless custom_attrs
/// already contains a Display derive. Structs use `{:?}` (Debug) as a fallback;
/// for enums and unions the caller supplies the match body via `match_arms`.
fn generate_display_impl(name: &str, custom_attrs: &Option<Vec<String>>, body: &str) -> String {
    // TODO: `.contains("Display")` is a loose heuristic - it correctly catches
    // `derive_more::Display` and `#[display(...)]` format attrs, but could
    // false-positive on unrelated attribute strings containing "Display".
    // The proper fix is a dedicated spec extension (`x-rust-display: false`)
    // that explicitly opts a type out of Display generation, rather than
    // inferring intent from x-rust-attrs content.
    let has_display = custom_attrs
        .as_ref()
        .is_some_and(|attrs| attrs.iter().any(|a| a.contains("Display")));
    if has_display {
        return String::new();
    }
    format!(
        "impl std::fmt::Display for {name} {{\n    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{\n{body}    }}\n}}\n"
    )
}

/// Generates custom attributes from x-rust-attrs
fn generate_custom_attrs(custom_attrs: &Option<Vec<String>>) -> String {
    if let Some(attrs) = custom_attrs {
        attrs
            .iter()
            .map(|attr| format!("{attr}\n"))
            .collect::<String>()
    } else {
        String::new()
    }
}

pub fn generate_models(
    models: &[ModelType],
    requests: &[RequestModel],
    responses: &[ResponseModel],
    mode: GenerateMode,
    display: bool,
) -> Result<String> {
    // First, generate all model code to determine which imports are needed
    let mut models_code = String::new();
    let mut required_uses = RequiredUses::empty();
    let mut needs_validator = false;
    let mut pattern_registry: IndexMap<String, String> = IndexMap::new();

    for model_type in models {
        match model_type {
            ModelType::Struct(model) => {
                models_code.push_str(&generate_model(
                    model,
                    &mut required_uses,
                    &mut needs_validator,
                    &mut pattern_registry,
                    display,
                )?);
            }
            ModelType::Union(union) => {
                models_code.push_str(&generate_union(union, display)?);
            }
            ModelType::Composition(comp) => {
                models_code.push_str(&generate_composition(comp, &mut required_uses, display)?);
            }
            ModelType::Enum(enum_model) => {
                models_code.push_str(&generate_enum(enum_model, display)?);
            }
            ModelType::TypeAlias(type_alias) => {
                models_code.push_str(&generate_type_alias(type_alias)?);
            }
        }
    }

    if mode.contains(GenerateMode::REQUESTS) {
        for request in requests {
            models_code.push_str(&generate_request_model(request)?);
        }
    }

    if mode.contains(GenerateMode::RESPONSES) {
        for response in responses {
            models_code.push_str(&generate_response_model(response)?);
        }
    }

    // Determine which imports are actually needed
    let needs_uuid = required_uses.contains(RequiredUses::UUID);
    let needs_datetime = required_uses.contains(RequiredUses::DATETIME);
    let needs_date = required_uses.contains(RequiredUses::DATE);

    // Build final output with only necessary imports
    let mut output = create_header();
    output.push_str("use serde::{Serialize, Deserialize};\n");

    if needs_uuid {
        output.push_str("use uuid::Uuid;\n");
    }

    if needs_validator {
        output.push_str("use validator::Validate;\n");
    }

    if !pattern_registry.is_empty() {
        output.push_str("use regex::Regex;\n");
        output.push_str("use std::sync::LazyLock;\n");
    }

    if needs_datetime || needs_date {
        output.push_str("use chrono::{");
        let mut chrono_imports = Vec::new();
        if needs_datetime {
            chrono_imports.push("DateTime");
        }
        if needs_date {
            chrono_imports.push("NaiveDate");
        }
        if needs_datetime {
            chrono_imports.push("Utc");
        }
        output.push_str(&chrono_imports.join(", "));
        output.push_str("};\n");
    }

    output.push('\n');

    // Static regex objects, one per unique pattern across all models.
    if !pattern_registry.is_empty() {
        for (pattern, name) in &pattern_registry {
            output.push_str(&format!(
                "static {name}: LazyLock<Regex> = LazyLock::new(|| Regex::new(r\"{pattern}\").unwrap());\n"
            ));
        }
        output.push('\n');
    }

    output.push_str(&models_code);

    Ok(output)
}

/// Format f64 as a Rust float literal, ensuring `0` becomes `0.0`.
fn format_f64_literal(v: f64) -> String {
    let s = v.to_string();
    if s.contains('.') || s.contains('e') || s.contains("inf") || s.contains("NaN") {
        s
    } else {
        format!("{v}.0")
    }
}

/// Generate validator attributes based on validation rules
/// Register a regex pattern and return the name of the static that holds its compiled `Regex`.
/// Patterns are deduplicated: the same pattern always maps to the same static.
fn register_pattern(pattern: &str, registry: &mut IndexMap<String, String>) -> String {
    if let Some(existing) = registry.get(pattern) {
        return existing.clone();
    }
    let name = format!("RE_{}", registry.len() + 1);
    registry.insert(pattern.to_string(), name.clone());
    name
}

fn generate_validator_attrs(
    rules: &crate::models::ValidationRules,
    field_type: &str,
    pattern_registry: &mut IndexMap<String, String>,
) -> String {
    let mut attrs = String::new();

    match field_type {
        "String" | "str" | "Option<String>" | "Option<str>" => {
            let mut length_attrs = Vec::new();
            if let Some(min) = rules.min_length {
                length_attrs.push(format!("min = {}", min));
            }
            if let Some(max) = rules.max_length {
                length_attrs.push(format!("max = {}", max));
            }
            if !length_attrs.is_empty() {
                attrs.push_str(&format!(
                    "    #[validate(length({}))]\n",
                    length_attrs.join(", ")
                ));
            }

            if rules.email {
                attrs.push_str("    #[validate(email)]\n");
            }

            if rules.url {
                attrs.push_str("    #[validate(url)]\n");
            }

            if let Some(pattern) = &rules.pattern {
                let static_name = register_pattern(pattern, pattern_registry);
                attrs.push_str(&format!("    #[validate(regex(path = {static_name}))]\n"));
            }
        }
        "i8" | "i16" | "i32" | "i64" | "u8" | "u16" | "u32" | "u64" | "Option<i8>"
        | "Option<i16>" | "Option<i32>" | "Option<i64>" | "Option<u8>" | "Option<u16>"
        | "Option<u32>" | "Option<u64>" => {
            let mut range_attrs = Vec::new();
            if let Some(min) = rules.minimum {
                range_attrs.push(format!("min = {}", min as i64));
            }
            if let Some(max) = rules.maximum {
                range_attrs.push(format!("max = {}", max as i64));
            }
            if rules.exclusive_minimum || rules.exclusive_maximum {
                range_attrs.push("exclusive = true".to_string());
            }
            if !range_attrs.is_empty() {
                attrs.push_str(&format!(
                    "    #[validate(range({}))]\n",
                    range_attrs.join(", ")
                ));
            }
        }
        "f32" | "f64" | "Option<f32>" | "Option<f64>" => {
            let mut range_attrs = Vec::new();
            if let Some(min) = rules.minimum {
                range_attrs.push(format!("min = {}", format_f64_literal(min)));
            }
            if let Some(max) = rules.maximum {
                range_attrs.push(format!("max = {}", format_f64_literal(max)));
            }
            if rules.exclusive_minimum || rules.exclusive_maximum {
                range_attrs.push("exclusive = true".to_string());
            }
            if !range_attrs.is_empty() {
                attrs.push_str(&format!(
                    "    #[validate(range({}))]\n",
                    range_attrs.join(", ")
                ));
            }
        }
        _ if field_type.contains("Vec<") => {
            let mut length_attrs = Vec::new();
            if let Some(min) = rules.min_items {
                length_attrs.push(format!("min = {}", min));
            }
            if let Some(max) = rules.max_items {
                length_attrs.push(format!("max = {}", max));
            }
            if !length_attrs.is_empty() {
                attrs.push_str(&format!(
                    "    #[validate(length({}))]\n",
                    length_attrs.join(", ")
                ));
            }
        }
        _ => {}
    }

    attrs
}

fn generate_model(
    model: &Model,
    required_uses: &mut RequiredUses,
    needs_validator: &mut bool,
    pattern_registry: &mut IndexMap<String, String>,
    display: bool,
) -> Result<String> {
    let mut output = String::new();

    output.push_str(&generate_description_docs(
        &model.description,
        &model.name,
        "",
    ));

    output.push_str(&generate_custom_attrs(&model.custom_attrs));

    // First pass over fields: resolve types and generate field bodies, tracking
    // whether any #[validate(...)] attrs are needed. This lets us emit the correct
    // derive line once without fragile byte-range patching.
    struct FieldOutput {
        body: String,
        needs_validate: bool,
    }
    let mut field_outputs: Vec<FieldOutput> = Vec::with_capacity(model.fields.len());

    for field in &model.fields {
        let field_type = match field.field_type.as_str() {
            "DateTime" | "DateTime<Utc>" => {
                *required_uses |= RequiredUses::DATETIME;
                "DateTime<Utc>"
            }
            "Date" => {
                *required_uses |= RequiredUses::DATE;
                "NaiveDate"
            }
            "Uuid" => {
                *required_uses |= RequiredUses::UUID;
                "Uuid"
            }
            _ => &field.field_type,
        };

        let mut lowercased_name = to_snake_case(field.name.as_str());
        if is_reserved_word(&lowercased_name) {
            lowercased_name = format!("r#{lowercased_name}")
        }

        let is_optional = !field.is_required || field.is_nullable;
        let base_type = if field.is_array_ref {
            format!("Vec<{field_type}>")
        } else {
            field_type.to_string()
        };
        let full_field_type = if is_optional {
            format!("Option<{base_type}>")
        } else {
            base_type
        };

        let mut field_body = String::new();
        field_body.push_str(&generate_description_docs(&field.description, "", "    "));

        if let Some(attrs) = &field.custom_attrs {
            for attr in attrs {
                field_body.push_str(&format!("    {attr}\n"));
            }
        }

        let mut needs_validate = false;
        if let Some(rules) = &field.validation_rules {
            let attrs = generate_validator_attrs(rules, &full_field_type, pattern_registry);
            if !attrs.is_empty() {
                needs_validate = true;
                field_body.push_str(&attrs);
            }
        }

        if lowercased_name != field.name {
            field_body.push_str(&format!("    #[serde(rename = \"{}\")]\n", field.name));
        }
        if field.should_flatten() {
            field_body.push_str("    #[serde(flatten)]\n");
        }
        field_body.push_str(&format!("    pub {lowercased_name}: {full_field_type},\n"));

        field_outputs.push(FieldOutput {
            body: field_body,
            needs_validate,
        });
    }

    let any_validate_attrs = field_outputs.iter().any(|f| f.needs_validate);

    if !has_custom_derive(&model.custom_attrs) {
        if any_validate_attrs {
            *needs_validator = true;
            output.push_str("#[derive(Debug, Clone, Serialize, Deserialize, Validate)]\n");
        } else {
            output.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
        }
    }

    output.push_str(&format!("pub struct {} {{\n", model.name));
    for fo in field_outputs {
        output.push_str(&fo.body);
    }

    output.push_str("}\n");
    if display {
        output.push_str(&generate_display_impl(
            &model.name,
            &model.custom_attrs,
            "        write!(f, \"{:?}\", self)\n",
        ));
    }
    output.push('\n');
    Ok(output)
}

fn generate_request_model(request: &RequestModel) -> Result<String> {
    let mut output = String::new();

    if request.name.is_empty() || request.name == EMPTY_REQUEST_NAME {
        return Ok(String::new());
    }

    output.push_str(&format!("/// {}\n", request.name));
    output.push_str("#[derive(Debug, Clone, Serialize)]\n");
    output.push_str(&format!("pub struct {} {{\n", request.name));
    output.push_str(&format!("    pub body: {},\n", request.schema));
    output.push_str("}\n");
    Ok(output)
}

fn generate_response_model(response: &ResponseModel) -> Result<String> {
    if response.name.is_empty() || response.name == EMPTY_RESPONSE_NAME {
        return Ok(String::new());
    }

    let type_name = format!("{}{}", response.name, response.status_code);

    let mut output = String::new();

    output.push_str(&generate_description_docs(
        &response.description,
        &type_name,
        "",
    ));

    output.push_str("#[derive(Debug, Clone, Deserialize)]\n");
    output.push_str(&format!("pub struct {type_name} {{\n"));
    output.push_str(&format!("    pub body: {},\n", response.schema));
    output.push_str("}\n");

    Ok(output)
}

fn generate_union(union: &UnionModel, display: bool) -> Result<String> {
    let mut output = String::new();

    output.push_str(&format!(
        "/// {} ({})\n",
        union.name,
        match union.union_type {
            UnionType::OneOf => "oneOf",
            UnionType::AnyOf => "anyOf",
        }
    ));
    output.push_str(&generate_custom_attrs(&union.custom_attrs));

    // Only add default derive if custom_attrs doesn't already contain a derive
    if !has_custom_derive(&union.custom_attrs) {
        output.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
    }

    // Only add default serde(untagged) if custom_attrs doesn't already contain a serde attribute
    if !has_custom_serde(&union.custom_attrs) {
        output.push_str("#[serde(untagged)]\n");
    }

    output.push_str(&format!("pub enum {} {{\n", union.name));

    for variant in &union.variants {
        match &variant.primitive_type {
            Some(t) => output.push_str(&format!("    {}({}),\n", variant.name, t)),
            None => output.push_str(&format!("    {}({}),\n", variant.name, variant.name)),
        }
    }

    output.push_str("}\n");

    if display {
        let match_arms = union
            .variants
            .iter()
            .map(|v| {
                format!(
                    "            Self::{}(inner) => write!(f, \"{{}}\", inner),\n",
                    v.name
                )
            })
            .collect::<String>();
        output.push_str(&generate_display_impl(
            &union.name,
            &union.custom_attrs,
            &format!("        match self {{\n{match_arms}        }}\n"),
        ));
    }

    Ok(output)
}

fn generate_composition(
    comp: &CompositionModel,
    required_uses: &mut RequiredUses,
    display: bool,
) -> Result<String> {
    let mut output = String::new();

    output.push_str(&format!("/// {} (allOf composition)\n", comp.name));
    output.push_str(&generate_custom_attrs(&comp.custom_attrs));

    // Only add default derive if custom_attrs doesn't already contain a derive
    if !has_custom_derive(&comp.custom_attrs) {
        output.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
    }

    output.push_str(&format!("pub struct {} {{\n", comp.name));

    for field in &comp.all_fields {
        let field_type = match field.field_type.as_str() {
            "String" => "String",
            "f64" => "f64",
            "i64" => "i64",
            "bool" => "bool",
            "DateTime" => {
                *required_uses |= RequiredUses::DATETIME;
                "DateTime<Utc>"
            }
            "Date" => {
                *required_uses |= RequiredUses::DATE;
                "NaiveDate"
            }
            "Uuid" => {
                *required_uses |= RequiredUses::UUID;
                "Uuid"
            }
            _ => &field.field_type,
        };

        let mut lowercased_name = to_snake_case(field.name.as_str());
        if is_reserved_word(&lowercased_name) {
            lowercased_name = format!("r#{lowercased_name}");
        }

        // Only add serde rename if the Rust field name differs from the original field name
        if lowercased_name != field.name {
            output.push_str(&format!("    #[serde(rename = \"{}\")]\n", field.name));
        }

        // Field-level custom attributes (e.g. #[serde(rename = "...")])
        if let Some(attrs) = &field.custom_attrs {
            for attr in attrs {
                output.push_str(&format!("    {attr}\n"));
            }
        }

        // If field references an array, wrap it in Vec<>
        if field.is_array_ref {
            if field.is_required && !field.is_nullable {
                output.push_str(&format!("    pub {lowercased_name}: Vec<{field_type}>,\n",));
            } else {
                output.push_str(&format!(
                    "    pub {lowercased_name}: Option<Vec<{field_type}>>,\n",
                ));
            }
        } else if field.is_required && !field.is_nullable {
            output.push_str(&format!("    pub {lowercased_name}: {field_type},\n",));
        } else {
            output.push_str(&format!(
                "    pub {lowercased_name}: Option<{field_type}>,\n",
            ));
        }
    }

    output.push_str("}\n");
    if display {
        output.push_str(&generate_display_impl(
            &comp.name,
            &comp.custom_attrs,
            "        write!(f, \"{:?}\", self)\n",
        ));
    }
    Ok(output)
}

fn generate_enum(enum_model: &EnumModel, display: bool) -> Result<String> {
    let mut output = String::new();

    output.push_str(&generate_description_docs(
        &enum_model.description,
        &enum_model.name,
        "",
    ));

    output.push_str(&generate_custom_attrs(&enum_model.custom_attrs));

    // Only add default derive if custom_attrs doesn't already contain a derive
    if !has_custom_derive(&enum_model.custom_attrs) {
        output.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
    }

    output.push_str(&format!("pub enum {} {{\n", enum_model.name));

    // Collect (rust_name, display_value) pairs for the Display impl below.
    let mut variant_display: Vec<(String, String)> = Vec::new();

    for (i, variant) in enum_model.variants.iter().enumerate() {
        let original = variant.clone();

        let mut rust_name = crate::parser::to_pascal_case(variant);

        let serde_rename = if is_reserved_word(&rust_name) {
            rust_name.push_str("Value");
            Some(original.clone())
        } else if rust_name != original {
            Some(original.clone())
        } else {
            None
        };

        let display_value = serde_rename
            .as_deref()
            .unwrap_or(&original)
            .replace('\\', "\\\\")
            .replace('"', "\\\"");
        variant_display.push((rust_name.clone(), display_value));

        if let Some(rename) = serde_rename {
            output.push_str(&format!("    #[serde(rename = \"{rename}\")]\n"));
        }

        if i + 1 == enum_model.variants.len() {
            output.push_str(&format!("    {rust_name}\n"));
        } else {
            output.push_str(&format!("    {rust_name},\n"));
        }
    }

    output.push_str("}\n");

    if display {
        let match_arms = variant_display
            .iter()
            .map(|(rust_name, display_value)| {
                format!("            Self::{rust_name} => write!(f, \"{display_value}\"),\n")
            })
            .collect::<String>();
        output.push_str(&generate_display_impl(
            &enum_model.name,
            &enum_model.custom_attrs,
            &format!("        match self {{\n{match_arms}        }}\n"),
        ));
    }

    Ok(output)
}

fn generate_type_alias(type_alias: &TypeAliasModel) -> Result<String> {
    let mut output = String::new();

    output.push_str(&generate_description_docs(
        &type_alias.description,
        &type_alias.name,
        "",
    ));

    output.push_str(&generate_custom_attrs(&type_alias.custom_attrs));
    output.push_str(&format!(
        "pub type {} = {};\n\n",
        type_alias.name, type_alias.target_type
    ));

    Ok(output)
}

pub fn generate_rust_code(models: &[Model]) -> Result<String> {
    let mut code = create_header();

    code.push_str("use serde::{Serialize, Deserialize};\n");
    code.push_str("use uuid::Uuid;\n");
    code.push_str("use chrono::{DateTime, NaiveDate, Utc};\n\n");

    for model in models {
        code.push_str(&format!("/// {}\n", model.name));
        code.push_str("#[derive(Debug, Clone, Serialize, Deserialize)]\n");
        code.push_str(&format!("pub struct {} {{\n", model.name));

        for field in &model.fields {
            let field_type = match field.field_type.as_str() {
                "String" => "String",
                "f64" => "f64",
                "i64" => "i64",
                "bool" => "bool",
                "DateTime" => "DateTime<Utc>",
                "Date" => "NaiveDate",
                "Uuid" => "Uuid",
                _ => &field.field_type,
            };

            let mut lowercased_name = to_snake_case(field.name.as_str());
            if is_reserved_word(&lowercased_name) {
                lowercased_name = format!("r#{lowercased_name}")
            }

            // Only add serde rename if the Rust field name differs from the original field name
            if lowercased_name != field.name {
                code.push_str(&format!("    #[serde(rename = \"{}\")]\n", field.name));
            }

            if field.is_required {
                code.push_str(&format!("    pub {lowercased_name}: {field_type},\n",));
            } else {
                code.push_str(&format!(
                    "    pub {lowercased_name}: Option<{field_type}>,\n",
                ));
            }
        }

        code.push_str("}\n\n");
    }

    Ok(code)
}

pub fn generate_lib() -> Result<String> {
    let mut code = create_header();
    code.push_str("pub mod models;\n");

    Ok(code)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::EnumModel;

    fn make_enum(variants: Vec<&str>) -> EnumModel {
        EnumModel {
            name: "TestEnum".to_string(),
            description: None,
            variants: variants.into_iter().map(String::from).collect(),
            custom_attrs: None,
        }
    }

    #[test]
    fn test_enum_display_escapes_quotes_and_backslashes() {
        // Enum values containing " or \ must be escaped in the generated write! string literal.
        let model = make_enum(vec!["normal", r#"with"quote"#, r"with\backslash"]);
        let output = generate_enum(&model, true).expect("generate_enum failed");

        assert!(
            output.contains(r#"write!(f, "with\"quote")"#),
            "double quote should be escaped in Display impl:\n{output}"
        );
        assert!(
            output.contains(r#"write!(f, "with\\backslash")"#),
            "backslash should be escaped in Display impl:\n{output}"
        );
        assert!(
            output.contains(r#"write!(f, "normal")"#),
            "plain value should be unmodified:\n{output}"
        );
    }

    #[test]
    fn test_enum_no_display_when_flag_off() {
        let model = make_enum(vec!["foo", "bar"]);
        let output = generate_enum(&model, false).expect("generate_enum failed");
        assert!(
            !output.contains("impl std::fmt::Display"),
            "Display impl should not be generated when display=false:\n{output}"
        );
    }

    #[test]
    fn test_enum_no_display_when_custom_attrs_has_display() {
        let mut model = make_enum(vec!["foo"]);
        model.custom_attrs = Some(vec![
            "#[derive(derive_more::Display, Debug, Clone)]".to_string()
        ]);
        let output = generate_enum(&model, true).expect("generate_enum failed");
        assert!(
            !output.contains("impl std::fmt::Display"),
            "Display impl should be skipped when x-rust-attrs already has Display:\n{output}"
        );
    }

    #[test]
    fn test_float_range_uses_float_literals() {
        // Regression test for issue #66: f64 fields must get float literals
        // (e.g. `min = 0.0`) so the `Validate` derive infers f64, not i32.
        let rules = crate::models::ValidationRules {
            minimum: Some(0.0),
            maximum: Some(100.0),
            ..Default::default()
        };

        // Non-optional f64
        let mut registry = IndexMap::new();
        let attrs = generate_validator_attrs(&rules, "f64", &mut registry);
        assert!(
            attrs.contains("min = 0.0"),
            "f64 min should be a float literal:\n{attrs}"
        );
        assert!(
            attrs.contains("max = 100.0"),
            "f64 max should be a float literal:\n{attrs}"
        );

        // Optional f64
        let mut registry = IndexMap::new();
        let attrs = generate_validator_attrs(&rules, "Option<f64>", &mut registry);
        assert!(
            attrs.contains("min = 0.0") && attrs.contains("max = 100.0"),
            "Option<f64> range should use float literals:\n{attrs}"
        );
    }

    #[test]
    fn test_integer_range_uses_integer_literals() {
        // Integer fields should keep integer literals (no `.0`).
        let rules = crate::models::ValidationRules {
            minimum: Some(0.0),
            maximum: Some(100.0),
            ..Default::default()
        };

        let mut registry = IndexMap::new();
        let attrs = generate_validator_attrs(&rules, "i64", &mut registry);
        assert!(
            attrs.contains("min = 0") && !attrs.contains("min = 0.0"),
            "i64 min should be an integer literal:\n{attrs}"
        );
        assert!(
            attrs.contains("max = 100") && !attrs.contains("max = 100.0"),
            "i64 max should be an integer literal:\n{attrs}"
        );
    }

    #[test]
    fn test_pattern_generates_validate_regex_with_static() {
        // Regression test for issue #67: pattern must emit `#[validate(regex(path = ...))]`
        // referencing a registered static, not the invalid `#[regex(...)]` attribute.
        let rules = crate::models::ValidationRules {
            pattern: Some(r"^[a-f0-9]{64}$".to_string()),
            ..Default::default()
        };

        let mut registry = IndexMap::new();
        let attrs = generate_validator_attrs(&rules, "String", &mut registry);

        assert!(
            attrs.contains("#[validate(regex(path = RE_1))]"),
            "should emit validate(regex(path = ...)):\n{attrs}"
        );
        assert!(
            !attrs.contains("#[regex("),
            "must not emit the invalid #[regex(...)] attribute:\n{attrs}"
        );
        assert_eq!(registry.len(), 1, "pattern should be registered");
        assert_eq!(registry.get(r"^[a-f0-9]{64}$"), Some(&"RE_1".to_string()));
    }

    #[test]
    fn test_identical_patterns_deduplicated() {
        // Two fields with the same pattern must share one static.
        let rules = crate::models::ValidationRules {
            pattern: Some(r"^[a-z]+$".to_string()),
            ..Default::default()
        };

        let mut registry = IndexMap::new();
        let _ = generate_validator_attrs(&rules, "String", &mut registry);
        let attrs2 = generate_validator_attrs(&rules, "String", &mut registry);

        assert_eq!(
            registry.len(),
            1,
            "identical patterns must share one static"
        );
        assert!(
            attrs2.contains("#[validate(regex(path = RE_1))]"),
            "second field should reuse RE_1:\n{attrs2}"
        );
    }

    #[test]
    fn test_distinct_patterns_get_distinct_statics() {
        let rules_a = crate::models::ValidationRules {
            pattern: Some(r"^[a-z]+$".to_string()),
            ..Default::default()
        };
        let rules_b = crate::models::ValidationRules {
            pattern: Some(r"^[0-9]+$".to_string()),
            ..Default::default()
        };

        let mut registry = IndexMap::new();
        let attrs_a = generate_validator_attrs(&rules_a, "String", &mut registry);
        let attrs_b = generate_validator_attrs(&rules_b, "String", &mut registry);

        assert!(
            attrs_a.contains("#[validate(regex(path = RE_1))]")
                && attrs_b.contains("#[validate(regex(path = RE_2))]"),
            "distinct patterns must get distinct statics:\n{attrs_a}\n{attrs_b}"
        );
    }
}