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
/*! Code generator from XML FIX dictionary spec file. */

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

use crate::converter::convert_spec;
use crate::model::*;

use bytes::Bytes;
use convert_case::{Case, Casing};
use itertools::Itertools;

mod converter;
mod model;

use quickfix_spec_parser::{FieldSpec, FieldType};

trait FieldAccessorGenerator {
    fn getter_prefix_text(&self) -> &'static str;
    fn setter_prefix_text(&self) -> &'static str;
    fn caller_suffix_text(&self) -> &'static str;
}

/// Take a FIX XML spec file as `src` parameter and generated code to `dst` parameter.
pub fn generate<S: AsRef<Path>, D: AsRef<Path>>(
    src: S,
    dst: D,
    begin_string: &str,
) -> io::Result<()> {
    let spec_data = fs::read(src)?;
    let spec = quickfix_spec_parser::parse_spec(&spec_data).expect("Cannot parse FIX spec");
    let spec = convert_spec(spec);

    // Generate the code.
    println!("Generating code ...");
    let mut output = String::with_capacity(5 << 20); // 5Mo initial buffer
    generate_root(&mut output, begin_string);
    generate_field_ids(&mut output, &spec.field_specs);
    generate_field_types(&mut output, &spec.field_specs);
    generate_headers(&mut output, &spec.headers);
    generate_trailers(&mut output, &spec.trailers);
    generate_messages(&mut output, &spec.messages);
    generate_message_cracker(&mut output, &spec.messages);

    // Spawn a rustfmt daemon.
    let mut rustfmt = process::Command::new("rustfmt")
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .spawn()?;

    // Send the code to rustfmt.
    println!("Formatting code ...");
    let mut rustfmt_in = rustfmt.stdin.take().expect("Fail to take rustfmt stdin");
    rustfmt_in.write_all(output.as_bytes())?;
    rustfmt_in.flush()?;
    drop(rustfmt_in); // Avoid infinite waiting !

    // Check output and write result.
    let rustfmt_out = rustfmt.wait_with_output()?;
    if !rustfmt_out.status.success() {
        println!("rustfmt stdout =======================");
        println!("{:?}", Bytes::from(rustfmt_out.stdout));
        println!("rustfmt stderr =======================");
        println!("{:?}", Bytes::from(rustfmt_out.stderr));

        panic!("Fail to run rustfmt");
    }

    // Write code to disk.
    println!("Writing code to disk ...");
    fs::write(dst, rustfmt_out.stdout)?;
    Ok(())
}

fn generate_root(output: &mut String, begin_string: &str) {
    output.push_str(&format!(
        r#" #[allow(unused_imports)]
            use quickfix::*;

            pub const FIX_BEGIN_STRING: &str = "{begin_string}";

            #[derive(Debug, PartialEq, Eq, Clone, Copy, Hash)]
            pub struct FixParseError;

            impl std::fmt::Display for FixParseError {{
                fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {{
                    writeln!(f, "FIX parse error")
                }}
            }}

            impl std::error::Error for FixParseError {{}}

            "#
    ))
}

fn generate_field_ids(output: &mut String, field_specs: &[FieldSpec]) {
    output.push_str("pub mod field_id {\n");

    for field_spec in field_specs {
        output.push_str(&format!(
            "pub const {}: i32 = {};\n",
            field_spec.name.to_case(Case::ScreamingSnake),
            field_spec.number
        ));
    }

    output.push_str("} // field_id\n\n");
}

fn generate_field_types(output: &mut String, field_specs: &[FieldSpec]) {
    output.push_str("pub mod field_types {\n");

    for field_spec in field_specs {
        if !field_spec.values.is_empty() {
            match &field_spec.r#type {
                FieldType::Int => {
                    generate_field_type_int_values(output, field_spec);
                }
                _ => {
                    generate_field_type_char_values(output, field_spec);
                }
            }
        } else {
            generate_field_type_alias(output, field_spec);
        }
    }

    output.push_str("} // field_types\n\n");
}

fn generate_field_type_int_values(output: &mut String, field_spec: &FieldSpec) {
    assert!(!field_spec.values.is_empty());
    assert!(matches!(field_spec.r#type, FieldType::Int));

    let enum_name = field_spec.name.as_str();

    // Generate enum possible values.
    output.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n");
    output.push_str(&format!("pub enum {enum_name} {{\n"));
    for value in &field_spec.values {
        output.push_str(&format!(
            "{} = {},\n",
            value.description.to_case(Case::UpperCamel),
            value.value
        ));
    }
    output.push_str("}\n\n");

    generate_field_type_values(output, field_spec);
}

fn generate_field_type_char_values(output: &mut String, field_spec: &FieldSpec) {
    assert!(!field_spec.values.is_empty());

    let enum_name = field_spec.name.as_str();

    // Generate enum possible values.
    output.push_str("#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]\n");
    output.push_str(&format!("pub enum {enum_name} {{\n"));
    for value in &field_spec.values {
        output.push_str(&format!(
            "{},\n",
            value.description.to_case(Case::UpperCamel)
        ));
    }
    output.push_str("}\n\n");

    generate_field_type_values(output, field_spec);
}

fn generate_field_type_values(output: &mut String, field_spec: &FieldSpec) {
    assert!(!field_spec.values.is_empty());

    let type_name = field_spec.name.as_str();

    // Generate method helpers.
    output.push_str(&format!(
        r#" impl {type_name} {{
                #[inline(always)]
                pub const fn from_const_bytes(s: &[u8]) -> Result<Self, crate::FixParseError> {{
                    match s {{
                    "#
    ));
    for value in &field_spec.values {
        output.push_str(&format!(
            "    b\"{}\" => Ok(Self::{}),\n",
            value.value,
            value.description.to_case(Case::UpperCamel),
        ));
    }
    output.push_str(
        r#"             _ => Err(crate::FixParseError),
                    }
                }
            }

            "#,
    );

    // Generate `FromStr`.
    output.push_str(&format!(
        r#" impl std::str::FromStr for {type_name} {{
                type Err = crate::FixParseError;
                fn from_str(s: &str) -> Result<Self, Self::Err> {{
                    Self::from_const_bytes(s.as_bytes())
                }}
            }}

            "#
    ));

    // Generate `IntoFixValue`.
    output.push_str(&format!(
        r#" impl quickfix::IntoFixValue for {type_name} {{
                fn into_fix_value(self) -> Result<std::ffi::CString, std::ffi::NulError> {{
                    std::ffi::CString::new(match self {{
                    "#
    ));
    for value in &field_spec.values {
        output.push_str(&format!(
            "    Self::{} => \"{}\",\n",
            value.description.to_case(Case::UpperCamel),
            value.value,
        ));
    }
    output.push_str(
        r#"         })
                }
            }

            "#,
    );
}

fn generate_field_type_alias(output: &mut String, field_spec: &FieldSpec) {
    assert!(field_spec.values.is_empty());

    let type_name = field_spec.name.as_str();
    let rust_type = match &field_spec.r#type {
        FieldType::Int => "i64",
        FieldType::Length => "u32",
        FieldType::SequenceNumber => "u32",
        FieldType::NumberInGroup => "i32",
        FieldType::Boolean => "bool",

        FieldType::Float
        | FieldType::Price
        | FieldType::Amount
        | FieldType::Quantity
        | FieldType::PriceOffset
        | FieldType::Percentage => "f64",

        FieldType::Char
        | FieldType::Data
        | FieldType::Time
        | FieldType::Date
        | FieldType::MonthYear
        | FieldType::DayOfMonth
        | FieldType::String
        | FieldType::Currency
        | FieldType::MultipleValueString
        | FieldType::Exchange
        | FieldType::LocalMarketDate
        | FieldType::UtcTimeStamp
        | FieldType::UtcDate
        | FieldType::UtcTimeOnly
        | FieldType::Country
        | FieldType::UtcDateOnly
        | FieldType::MultipleCharValue
        | FieldType::MultipleStringValue
        | FieldType::TzTimeOnly
        | FieldType::TzTimestamp
        | FieldType::XmlData
        | FieldType::Language
        | FieldType::TagNumber
        | FieldType::XidRef
        | FieldType::Xid
        | FieldType::LocalMarketTime => "String",
        x => unimplemented!("Unsupported FieldType: {x:?}"),
    };

    output.push_str(&format!("pub type {type_name} = {rust_type};\n\n"));
}

fn generate_headers(output: &mut String, components: &[SubComponent]) {
    struct Accessor;

    impl FieldAccessorGenerator for Accessor {
        fn getter_prefix_text(&self) -> &'static str {
            "inner.with_header(|x| x."
        }
        fn setter_prefix_text(&self) -> &'static str {
            "inner.with_header_mut(|x| x."
        }
        fn caller_suffix_text(&self) -> &'static str {
            ")"
        }
    }

    generate_message_wrapper(output, "Header", components, &Accessor);
}

fn generate_trailers(output: &mut String, components: &[SubComponent]) {
    struct Accessor;

    impl FieldAccessorGenerator for Accessor {
        fn getter_prefix_text(&self) -> &'static str {
            "inner.with_trailer(|x| x."
        }
        fn setter_prefix_text(&self) -> &'static str {
            "inner.with_trailer_mut(|x| x."
        }
        fn caller_suffix_text(&self) -> &'static str {
            ")"
        }
    }

    generate_message_wrapper(output, "Trailer", components, &Accessor);
}

fn generate_message_wrapper(
    output: &mut String,
    struct_name: &str,
    components: &[SubComponent],
    accessor: &impl FieldAccessorGenerator,
) {
    output.push_str(&format!(
        r#" #[derive(Debug)]
            pub struct {struct_name}<'a> {{ inner: &'a quickfix::Message }}

            "#
    ));

    generate_sub_components(output, &struct_name.to_case(Case::Snake), components);

    output.push_str(&format!("impl {struct_name}<'_> {{\n"));
    generate_components_getters(output, struct_name, components, accessor);
    output.push_str("}\n\n");

    output.push_str(&format!(
        r#" #[derive(Debug)]
            pub struct {struct_name}Mut<'a> {{ inner: &'a mut quickfix::Message }}

            "#
    ));

    output.push_str(&format!("impl {struct_name}Mut<'_> {{\n"));
    generate_components_setters(output, struct_name, components, accessor);
    output.push_str("}\n\n");
}

fn generate_messages(output: &mut String, messages: &[MessageSpec]) {
    for message in messages {
        generate_message(output, message);
    }
}

fn generate_message(output: &mut String, message: &MessageSpec) {
    let struct_name = message.name.as_str();
    let msg_type = message.msg_type.as_str();

    // Generate main struct content.
    output.push_str(&format!(
        r#" #[derive(Debug, Clone)]
            pub struct {struct_name} {{
                inner: quickfix::Message,
            }}

            impl {struct_name} {{
                pub const MSG_TYPE_BYTES: &'static str = "{msg_type}";
                pub const MSG_TYPE: crate::field_types::MsgType =
                    match crate::field_types::MsgType::from_const_bytes(Self::MSG_TYPE_BYTES.as_bytes()) {{
                        Ok(value) => value,
                        Err(_) => panic!("Invalid message type for {struct_name}"),
                    }};

                #[inline(always)]
                pub fn header(&mut self) -> Header {{
                    Header {{ inner: &self.inner }}
                }}

                #[inline(always)]
                pub fn header_mut(&mut self) -> HeaderMut {{
                    HeaderMut {{ inner: &mut self.inner }}
                }}

                #[inline(always)]
                pub fn trailer(&mut self) -> Trailer {{
                    Trailer {{ inner: &self.inner }}
                }}

                #[inline(always)]
                pub fn trailer_mut(&mut self) -> TrailerMut {{
                    TrailerMut {{ inner: &mut self.inner }}
                }}

                /// Convert inner message as FIX text.
                ///
                /// This method is only here for debug / tests purposes. Do not use this
                /// in real production code.
                #[inline(never)]
                pub fn to_fix_string(&self) -> String {{
                    self.inner
                        .to_fix_string()
                        .expect("Fail to format {struct_name} message as FIX string")
                }}
            }}

            impl From<{struct_name}> for quickfix::Message {{
                fn from(input: {struct_name}) -> Self {{
                    input.inner
                }}
            }}

            impl From<quickfix::Message> for {struct_name} {{
                fn from(input: quickfix::Message) -> Self {{
                    assert_eq!(
                        input
                            .with_header(|h| h.get_field(field_id::MSG_TYPE))
                            .and_then(|x| crate::field_types::MsgType::from_const_bytes(x.as_bytes()).ok()),
                        Some(Self::MSG_TYPE),
                    );
                    Self {{ inner: input }}
                }}
            }}

            "#
    ));

    // Generate default constructor
    let required_params = format_required_params(&message.components);
    let new_setters = format_new_setters(&message.components);

    output.push_str(&format!(
        r#" impl {struct_name} {{
                #[allow(clippy::too_many_arguments)]
                pub fn try_new({required_params}) -> Result<Self, quickfix::QuickFixError> {{
                    let mut inner = quickfix::Message::new();

                    // Set headers (most of them will be set by quickfix library).
                    inner.with_header_mut(|h| {{
                        h.set_field(crate::field_id::BEGIN_STRING, crate::FIX_BEGIN_STRING)
                    }})?;
                    inner.with_header_mut(|h| {{
                        h.set_field(crate::field_id::MSG_TYPE, Self::MSG_TYPE)
                    }})?;

                    // Set required attributes.
                    {new_setters}

                    Ok(Self {{ inner }})
                }}
            }}

            "#
    ));

    // Generate getter / setters and sub-components.
    struct Accessor;

    impl FieldAccessorGenerator for Accessor {
        fn getter_prefix_text(&self) -> &'static str {
            "inner."
        }
        fn setter_prefix_text(&self) -> &'static str {
            "inner."
        }
        fn caller_suffix_text(&self) -> &'static str {
            ""
        }
    }

    generate_sub_components(
        output,
        &message.name.to_case(Case::Snake),
        &message.components,
    );

    output.push_str(&format!("impl {struct_name} {{\n\n"));
    generate_components_getters(output, struct_name, &message.components, &Accessor);
    generate_components_setters(output, struct_name, &message.components, &Accessor);
    output.push_str("}\n\n");
}

fn generate_group(output: &mut String, group: &MessageGroup) {
    let struct_name = group.name.as_str();
    let group_id = format_field_id(&group.name);
    let group_delim = format_field_id(
        group
            .components
            .first()
            .expect("Group cannot be empty")
            .name(),
    );
    let group_value_ids = group
        .components
        .iter()
        .map(|x| format_field_id(x.name()))
        .join(",");

    // Generate main struct.
    let required_params = format_required_params(&group.components);
    let new_setters = format_new_setters(&group.components);

    output.push_str(&format!(
        r#" #[derive(Debug, Clone)]
            pub struct {struct_name} {{
                pub(crate) inner: quickfix::Group,
            }}

            impl {struct_name} {{
                pub const FIELD_ID: i32 = {group_id};
                pub const DELIMITER: i32 = {group_delim};

                #[allow(clippy::too_many_arguments)]
                pub fn try_new({required_params}) -> Result<Self, quickfix::QuickFixError> {{
                    #[allow(unused_mut)]
                    let mut inner = quickfix::Group::try_with_orders(
                        Self::FIELD_ID,
                        Self::DELIMITER,
                        &[{group_value_ids}],
                    ).expect("Fail to build group {struct_name}");

                    {new_setters}

                    Ok(Self {{ inner }})
                }}
            }}

            "#
    ));

    // Generate getter / setters and sub-components.
    struct Accessor;

    impl FieldAccessorGenerator for Accessor {
        fn getter_prefix_text(&self) -> &'static str {
            "inner."
        }
        fn setter_prefix_text(&self) -> &'static str {
            "inner."
        }
        fn caller_suffix_text(&self) -> &'static str {
            ""
        }
    }

    generate_sub_components(output, &group.name.to_case(Case::Snake), &group.components);

    output.push_str(&format!("impl {struct_name} {{\n\n"));
    generate_components_getters(output, struct_name, &group.components, &Accessor);
    generate_components_setters(output, struct_name, &group.components, &Accessor);
    output.push_str("}\n\n");
}

fn generate_sub_components(output: &mut String, module_name: &str, components: &[SubComponent]) {
    // Check if message has some sub components
    if components
        .iter()
        .any(|x| matches!(x, SubComponent::Group(_)))
    {
        // Create dedicate module for the component.
        output.push_str(&format!(
            r#" pub mod {module_name} {{
                    use super::*;

                    "#
        ));

        for value in components {
            match value {
                SubComponent::Field(_) => {} // There is no sub-components to generate for a basic field
                SubComponent::Group(x) => {
                    generate_group(output, x);
                }
            }
        }
        output.push_str("}\n\n");
    }
}

fn generate_components_getters(
    output: &mut String,
    struct_name: &str,
    components: &[SubComponent],
    accessor: &impl FieldAccessorGenerator,
) {
    for component in components {
        match component {
            SubComponent::Field(x) => {
                generate_field_getter(output, &x.name, x.required, accessor);
            }
            SubComponent::Group(x) => {
                generate_group_reader(output, struct_name, x);
            }
        }
    }
}

fn generate_components_setters(
    output: &mut String,
    struct_name: &str,
    components: &[SubComponent],
    accessor: &impl FieldAccessorGenerator,
) {
    for component in components {
        match component {
            SubComponent::Field(x) => {
                generate_field_setters(output, x, accessor);
            }
            SubComponent::Group(x) => {
                generate_fn_add_group(output, struct_name, x);
            }
        }
    }
}

fn generate_field_getter(
    output: &mut String,
    field_name: &str,
    field_required: bool,
    accessor: &impl FieldAccessorGenerator,
) {
    // Eval trait and make some string alias.
    let call_get_prefix = accessor.getter_prefix_text();
    let call_suffix = accessor.caller_suffix_text();

    let fun_name_suffix = field_name.to_case(Case::Snake);
    let field_type = format!("crate::field_types::{field_name}");
    let field_id = format_field_id(field_name);

    // Generate code.
    if field_required {
        // Generate a getter that `panic()` if field is not set.
        output.push_str(&format!(
            r#" #[inline(always)]
                pub fn get_{fun_name_suffix}(&self) -> {field_type} {{
                    self.{call_get_prefix}get_field({field_id}){call_suffix}
                       .and_then(|x| x.parse().ok())
                       .expect("{field_id} is required but it is missing")
                }}

                "#
        ));
    } else {
        // Generate an optional getter.
        output.push_str(&format!(
            r#" #[inline(always)]
                pub fn get_{fun_name_suffix}(&self) -> Option<{field_type}> {{
                    self.{call_get_prefix}get_field({field_id}){call_suffix}
                       .and_then(|x| x.parse().ok())
                }}

                "#
        ));
    }
}

fn generate_field_setters(
    output: &mut String,
    field: &MessageField,
    accessor: &impl FieldAccessorGenerator,
) {
    // Eval trait and make some string alias.
    let call_set_prefix = accessor.setter_prefix_text();
    let call_suffix = accessor.caller_suffix_text();

    let fun_name_suffix = field.name.to_case(Case::Snake);
    let field_type = format!("crate::field_types::{}", field.name);
    let field_id = format_field_id(&field.name);

    // Generate code.
    output.push_str(&format!(
        r#" #[inline(always)]
            pub fn set_{fun_name_suffix}(&mut self, value: {field_type}) -> Result<&Self, quickfix::QuickFixError> {{
                self.{call_set_prefix}set_field({field_id}, value){call_suffix}?;
                Ok(self)
            }}

            "#
    ));

    // If field is optional, we can generate a remover.
    if !field.required {
        output.push_str(&format!(
            r#" #[inline(always)]
                pub fn remove_{fun_name_suffix}(&mut self) -> Result<&Self, quickfix::QuickFixError> {{
                    self.{call_set_prefix}remove_field({field_id}){call_suffix}?;
                    Ok(self)
                }}

                "#
        ));
    }
}

fn generate_group_reader(output: &mut String, struct_name: &str, group: &MessageGroup) {
    // Add some type alias.
    let fun_name_suffix = group.name.to_case(Case::Snake);
    let group_type = format!("self::{}::{}", struct_name.to_case(Case::Snake), group.name);

    // Generate code.
    output.push_str(&format!(
        r#" #[inline(always)]
            pub fn clone_group_{fun_name_suffix}(&self, index: usize) -> Option<{group_type}> {{
                self.inner
                    .clone_group(index as i32, {group_type}::FIELD_ID)
                    .map(|raw_group| {group_type} {{ inner: raw_group }})
            }}

            "#
    ));
}

fn generate_fn_add_group(output: &mut String, struct_name: &str, group: &MessageGroup) {
    // Add some type alias.
    let fun_name = format!("add_{}", group.name.to_case(Case::Snake));
    let group_type = format!("self::{}::{}", struct_name.to_case(Case::Snake), group.name);

    // Generate code.
    output.push_str(&format!(
        r#" #[inline(always)]
            pub fn {fun_name}(&mut self, value: {group_type}) -> Result<&Self, quickfix::QuickFixError> {{
                self.inner.add_group(&value.inner)?;
                Ok(self)
            }}

            "#
    ));
}

fn generate_message_cracker(output: &mut String, messages: &[MessageSpec]) {
    // Generate enum with all possible messages.
    output.push_str(
        r#" #[derive(Debug, Clone)]
            pub enum Messages {
            "#,
    );
    for message in messages {
        let struct_name = &message.name;

        output.push_str(&format!("  {struct_name}({struct_name}),\n"));
    }
    output.push_str(
        r#" }
            "#,
    );

    // Generate decode helpers.
    output.push_str(
        r#" impl Messages {
                /// Try decoding input message or return the message if it does not match any known message type.
                pub fn decode(input: quickfix::Message) -> Result<Self, quickfix::Message> {
                    match input
                        .with_header(|h| h.get_field(crate::field_id::MSG_TYPE))
                        .as_deref()
                    {
            "#,
    );
    for message in messages {
        let struct_name = &message.name;
        let message_type = &message.msg_type;

        output.push_str(&format!(
            "  Some(\"{message_type}\") => Ok(Self::{struct_name}(input.into())),\n"
        ));
    }
    output.push_str(
        r#"             _ => Err(input),
                    }
                }
            }
            "#,
    );
}

fn format_field_id(input: &str) -> String {
    format!("crate::field_id::{}", input.to_case(Case::ScreamingSnake))
}

fn format_required_params(components: &[SubComponent]) -> String {
    components
        .iter()
        .filter(|x| x.is_required())
        .map(|x| {
            let name = x.name();
            let param_name = name.to_case(Case::Snake);
            format!("{param_name}: crate::field_types::{name}")
        })
        .join(", ")
}

fn format_new_setters(components: &[SubComponent]) -> String {
    components
        .iter()
        .filter(|x| x.is_required())
        .map(|x| {
            let name = x.name();
            let field_id = format_field_id(name);
            let param_name = name.to_case(Case::Snake);
            format!("inner.set_field({field_id}, {param_name})?;")
        })
        .join("\n")
}