quickfix-tokio 0.2.0

A pure-Rust FIX protocol engine built natively on tokio
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
//! Code generator: FIX spec XML -> typed Rust module.
//!
//! Usage: `cargo run --bin generate-fix -- spec/FIX44.xml src/fix44`
//!
//! Emits `fields.rs` (field marker types + enum value constants),
//! `messages.rs` (one module per message with typed accessors, constructors
//! for required fields, and repeating-group structs), and `mod.rs`
//! (re-exports plus an `AnyMessage` classifier). The output is committed;
//! re-run when the spec changes.

use std::collections::{BTreeMap, HashSet};
use std::fmt::Write as _;

use quickfix_tokio::datadictionary::{DataDictionary, FieldDef, FieldType, GroupDef, MessageDef};
use quickfix_tokio::message::Tag;

fn main() {
    let args: Vec<String> = std::env::args().collect();
    if args.len() != 3 {
        eprintln!("usage: generate-fix <spec.xml> <out_dir>");
        std::process::exit(2);
    }
    let spec_path = &args[1];
    let out_dir = std::path::Path::new(&args[2]);

    let text = std::fs::read_to_string(spec_path).expect("read spec");
    let dd = DataDictionary::parse(&text).expect("parse spec");
    std::fs::create_dir_all(out_dir).expect("create out dir");

    let generator = Generator { dd };
    std::fs::write(out_dir.join("fields.rs"), generator.gen_fields()).expect("write fields.rs");
    std::fs::write(out_dir.join("messages.rs"), generator.gen_messages()).expect("write messages.rs");
    std::fs::write(out_dir.join("mod.rs"), generator.gen_mod()).expect("write mod.rs");
    println!(
        "generated {} fields, {} messages from {} into {}",
        generator.dd.fields_by_tag.len(),
        generator.dd.messages.len(),
        spec_path,
        out_dir.display()
    );
}

struct Generator {
    dd: DataDictionary,
}

const HEADER: &str = "//! GENERATED by `generate-fix` — do not edit by hand.\n\
                      #![allow(clippy::all, unused_imports, unused_mut, dead_code, non_upper_case_globals)]\n\n";

/// Rust value type for a dictionary field type.
fn value_type(ft: FieldType) -> &'static str {
    match ft {
        FieldType::Int
        | FieldType::Length
        | FieldType::SeqNum
        | FieldType::NumInGroup
        | FieldType::DayOfMonth => "i64",
        // FIX float-family fields use the crate's Amount alias (exact
        // rust_decimal::Decimal by default, or f64 without the feature).
        FieldType::Float
        | FieldType::Qty
        | FieldType::Price
        | FieldType::PriceOffset
        | FieldType::Amt
        | FieldType::Percentage => "crate::Amount",
        FieldType::Char => "char",
        FieldType::Boolean => "bool",
        FieldType::UtcTimestamp => "crate::UtcTimestamp",
        FieldType::UtcDateOnly | FieldType::LocalMktDate => "crate::FixDate",
        FieldType::Data => "Vec<u8>",
        _ => "String",
    }
}

/// Setter parameter style: (parameter type, conversion suffix).
fn param_style(ft: FieldType) -> (String, &'static str) {
    match value_type(ft) {
        "String" => ("impl Into<String>".into(), ".into()"),
        "Vec<u8>" => ("impl Into<Vec<u8>>".into(), ".into()"),
        other => (other.into(), ""),
    }
}

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

fn snake(name: &str) -> String {
    let chars: Vec<char> = name.chars().collect();
    let mut out = String::new();
    for (i, &c) in chars.iter().enumerate() {
        if c.is_ascii_uppercase() {
            let prev_lower = i > 0 && (chars[i - 1].is_ascii_lowercase() || chars[i - 1].is_ascii_digit());
            let next_lower = chars.get(i + 1).is_some_and(|n| n.is_ascii_lowercase());
            let prev_upper = i > 0 && chars[i - 1].is_ascii_uppercase();
            // "NoPartyIDs" is no_party_ids, not no_party_i_ds: a lone 's'
            // ending an acronym run stays attached to it.
            let acronym_plural = chars.get(i + 1) == Some(&'s')
                && !chars.get(i + 2).is_some_and(|n| n.is_ascii_lowercase());
            if prev_lower || (prev_upper && next_lower && !acronym_plural) {
                out.push('_');
            }
            out.push(c.to_ascii_lowercase());
        } else {
            out.push(c);
        }
    }
    if KEYWORDS.contains(&out.as_str()) {
        out.push('_');
    }
    out
}

/// Enum value description -> Rust const name.
fn const_name(value: &str, description: &str) -> String {
    let base = if description.is_empty() { format!("VALUE_{value}") } else { description.into() };
    let mut out = String::new();
    for c in base.chars() {
        if c.is_ascii_alphanumeric() {
            out.push(c.to_ascii_uppercase());
        } else if !out.ends_with('_') {
            out.push('_');
        }
    }
    let out = out.trim_matches('_').to_string();
    if out.is_empty() {
        return format!("VALUE_{}", value.replace(|c: char| !c.is_ascii_alphanumeric(), "_"));
    }
    if out.chars().next().unwrap().is_ascii_digit() { format!("_{out}") } else { out }
}

impl Generator {
    fn fields_sorted(&self) -> BTreeMap<Tag, &FieldDef> {
        self.dd.fields_by_tag.iter().map(|(t, f)| (*t, f)).collect()
    }

    fn field(&self, tag: Tag) -> &FieldDef {
        &self.dd.fields_by_tag[&tag]
    }

    // ----- fields.rs -----

    fn gen_fields(&self) -> String {
        let mut out = String::from(HEADER);
        out.push_str("//! Typed field markers: `fields::ClOrdID::TAG` etc, with enum value\n//! constants attached (`fields::Side::BUY`).\n\n");
        out.push_str("use crate::field_map::Field;\nuse crate::message::Tag;\n\n");

        for (tag, f) in self.fields_sorted() {
            let vt = value_type(f.field_type);
            writeln!(out, "/// {} ({tag}).\npub struct {};", f.name, f.name).unwrap();
            writeln!(
                out,
                "impl Field for {} {{ const TAG: Tag = {tag}; type Value = {vt}; }}",
                f.name
            )
            .unwrap();
            if !f.enum_values.is_empty() && matches!(vt, "char" | "String" | "i64") {
                let mut seen = HashSet::new();
                writeln!(out, "impl {} {{", f.name).unwrap();
                for (value, description) in &f.enum_values {
                    let name = const_name(value, description);
                    if !seen.insert(name.clone()) {
                        continue;
                    }
                    match vt {
                        "char" if value.len() == 1 => writeln!(
                            out,
                            "    pub const {name}: char = '{}';",
                            value.replace('\'', "\\'")
                        )
                        .unwrap(),
                        "i64" if value.parse::<i64>().is_ok() => {
                            writeln!(out, "    pub const {name}: i64 = {value};").unwrap()
                        }
                        _ => writeln!(
                            out,
                            "    pub const {name}: &'static str = {value:?};"
                        )
                        .unwrap(),
                    }
                }
                out.push_str("}\n");
            }
            out.push('\n');
        }
        out
    }

    // ----- messages.rs -----

    fn gen_messages(&self) -> String {
        let mut out = String::from(HEADER);
        out.push_str("//! One module per message; structs wrap [`crate::Message`] and expose\n//! typed accessors. Constructors take the message's required fields.\n\n");

        let by_name: BTreeMap<&str, &MessageDef> =
            self.dd.messages.values().map(|m| (m.name.as_str(), m)).collect();

        for def in by_name.values() {
            let mod_name = snake(&def.name);
            writeln!(out, "pub mod {mod_name} {{").unwrap();
            out.push_str(
                "    use crate::field_map::{Field, FieldMap};\n    use crate::error::ConversionError;\n    use super::super::fields;\n\n",
            );
            self.gen_message_struct(&mut out, def);
            // Repeating groups (and their nested groups).
            for counter in def.field_order.iter().filter(|t| def.groups.contains_key(t)) {
                let group = &def.groups[counter];
                self.gen_group_struct(&mut out, group, "");
            }
            out.push_str("}\n");
            writeln!(out, "pub use {mod_name}::{};\n", def.name).unwrap();
        }
        out
    }

    fn gen_message_struct(&self, out: &mut String, def: &MessageDef) {
        let name = &def.name;
        writeln!(out, "    /// {} (35={}).", name, def.msg_type).unwrap();
        writeln!(out, "    #[derive(Debug, Clone)]\n    pub struct {name}(pub crate::Message);").unwrap();
        writeln!(out, "    impl {name} {{").unwrap();
        writeln!(out, "        pub const MSG_TYPE: &'static str = {:?};", def.msg_type).unwrap();

        // Constructor with required scalar fields (groups added afterwards).
        let required: Vec<Tag> = def
            .required
            .iter()
            .filter(|t| !def.groups.contains_key(t))
            .copied()
            .collect();
        let args = required
            .iter()
            .map(|&t| {
                let f = self.field(t);
                let (pt, _) = param_style(f.field_type);
                format!("{}: {pt}", snake(&f.name))
            })
            .collect::<Vec<_>>()
            .join(", ");
        writeln!(out, "        #[allow(clippy::too_many_arguments)]").unwrap();
        writeln!(out, "        pub fn new({args}) -> Self {{").unwrap();
        writeln!(out, "            let mut m = crate::Message::with_type(Self::MSG_TYPE);").unwrap();
        for &t in &required {
            let f = self.field(t);
            let (_, conv) = param_style(f.field_type);
            writeln!(
                out,
                "            m.body.set_field::<fields::{}>({}{conv});",
                f.name,
                snake(&f.name)
            )
            .unwrap();
        }
        out.push_str("            Self(m)\n        }\n\n");

        // Conversion from a generic message.
        writeln!(
            out,
            "        /// Wrap a generic message; fails unless 35={:?}.\n        \
             pub fn from_message(msg: crate::Message) -> Result<Self, crate::Message> {{\n            \
             if msg.msg_type().ok().as_deref() == Some(Self::MSG_TYPE) {{ Ok(Self(msg)) }} else {{ Err(msg) }}\n        }}\n",
            def.msg_type
        )
        .unwrap();

        // Scalar field accessors.
        for &t in &def.field_order {
            if def.groups.contains_key(&t) {
                self.gen_group_accessors(out, &def.groups[&t], "self.0.body");
            } else {
                self.gen_field_accessors(out, t, "self.0.body");
            }
        }
        out.push_str("    }\n");

        // Deref/From glue.
        writeln!(
            out,
            "    impl std::ops::Deref for {name} {{\n        type Target = crate::Message;\n        \
             fn deref(&self) -> &crate::Message {{ &self.0 }}\n    }}\n    \
             impl std::ops::DerefMut for {name} {{\n        \
             fn deref_mut(&mut self) -> &mut crate::Message {{ &mut self.0 }}\n    }}\n    \
             impl From<{name}> for crate::Message {{\n        \
             fn from(m: {name}) -> crate::Message {{ m.0 }}\n    }}\n"
        )
        .unwrap();
    }

    fn gen_field_accessors(&self, out: &mut String, tag: Tag, map: &str) {
        let f = self.field(tag);
        let method = snake(&f.name);
        let vt = value_type(f.field_type);
        let (pt, conv) = param_style(f.field_type);
        writeln!(
            out,
            "        pub fn {method}(&self) -> Result<{vt}, ConversionError> {{ {map}.get_field::<fields::{}>() }}",
            f.name
        )
        .unwrap();
        writeln!(
            out,
            "        pub fn set_{method}(&mut self, v: {pt}) {{ {map}.set_field::<fields::{}>(v{conv}); }}",
            f.name
        )
        .unwrap();
        writeln!(
            out,
            "        pub fn has_{method}(&self) -> bool {{ {map}.has_field::<fields::{}>() }}",
            f.name
        )
        .unwrap();
    }

    fn gen_group_accessors(&self, out: &mut String, group: &GroupDef, map: &str) {
        let counter_field = self.field(group.counter);
        let method = snake(&counter_field.name);
        let struct_name = &counter_field.name;
        writeln!(
            out,
            "        pub fn {method}(&self) -> Result<Vec<{struct_name}>, ConversionError> {{\n            \
             Ok({map}.read_groups(&{method}_template())?.into_iter().map({struct_name}).collect())\n        }}",
        )
        .unwrap();
        writeln!(
            out,
            "        pub fn set_{method}(&mut self, groups: impl IntoIterator<Item = {struct_name}>) {{\n            \
             let maps: Vec<FieldMap> = groups.into_iter().map(|g| g.0).collect();\n            \
             {map}.write_groups(&{method}_template(), &maps);\n        }}",
        )
        .unwrap();
    }

    /// A repeating-group struct plus its flattened template fn. Nested group
    /// structs get the parent's name as a prefix to stay unique per module.
    fn gen_group_struct(&self, out: &mut String, group: &GroupDef, prefix: &str) {
        let counter_field = self.field(group.counter);
        let struct_name = format!("{prefix}{}", counter_field.name);
        let method = snake(&struct_name);

        // Template: counter + all members flattened in order.
        let mut members: Vec<Tag> = Vec::new();
        flatten_members(group, &mut members);
        writeln!(
            out,
            "\n    pub(crate) fn {method}_template() -> crate::GroupTemplate {{\n        \
             crate::GroupTemplate::new({}, vec![{}])\n    }}",
            group.counter,
            members.iter().map(|t| t.to_string()).collect::<Vec<_>>().join(", ")
        )
        .unwrap();

        writeln!(
            out,
            "    /// Repeating group counted by {} ({}). Set the delimiter\n    /// field ({}) first.\n    \
             #[derive(Debug, Clone, Default)]\n    pub struct {struct_name}(pub FieldMap);",
            counter_field.name, group.counter, group.delimiter
        )
        .unwrap();
        writeln!(out, "    impl {struct_name} {{").unwrap();
        writeln!(out, "        pub fn new() -> Self {{ Self(FieldMap::new()) }}").unwrap();
        for &t in &group.member_order {
            if group.groups.contains_key(&t) {
                let nested = &group.groups[&t];
                let nested_field = self.field(nested.counter);
                let nested_struct = format!("{}{}", counter_field.name, nested_field.name);
                let nested_method = snake(&nested_struct);
                writeln!(
                    out,
                    "        pub fn {nested_method}(&self) -> Result<Vec<{nested_struct}>, ConversionError> {{\n            \
                     Ok(self.0.read_groups(&{nested_method}_template())?.into_iter().map({nested_struct}).collect())\n        }}",
                )
                .unwrap();
                writeln!(
                    out,
                    "        pub fn set_{nested_method}(&mut self, groups: impl IntoIterator<Item = {nested_struct}>) {{\n            \
                     let maps: Vec<FieldMap> = groups.into_iter().map(|g| g.0).collect();\n            \
                     self.0.write_groups(&{nested_method}_template(), &maps);\n        }}",
                )
                .unwrap();
            } else {
                self.gen_field_accessors(out, t, "self.0");
            }
        }
        out.push_str("    }\n");

        // Nested group structs, prefixed by this group's name.
        for &t in &group.member_order {
            if let Some(nested) = group.groups.get(&t) {
                self.gen_group_struct(out, nested, &counter_field.name);
            }
        }
    }

    // ----- mod.rs -----

    fn gen_mod(&self) -> String {
        let mut out = String::from(HEADER);
        writeln!(
            out,
            "//! Typed messages for {} — generated from its spec XML.\n",
            self.dd.begin_string
        )
        .unwrap();
        out.push_str("pub mod fields;\npub mod messages;\npub use messages::*;\n\n");
        writeln!(out, "pub const BEGIN_STRING: &str = {:?};\n", self.dd.begin_string).unwrap();

        let by_name: BTreeMap<&str, &MessageDef> =
            self.dd.messages.values().map(|m| (m.name.as_str(), m)).collect();

        out.push_str("/// Every message type of this FIX version, for typed dispatch.\n#[derive(Debug, Clone)]\npub enum AnyMessage {\n");
        for def in by_name.values() {
            writeln!(out, "    {}(messages::{}::{}),", def.name, snake(&def.name), def.name).unwrap();
        }
        out.push_str("    /// MsgType not defined by this dictionary.\n    Unknown(crate::Message),\n}\n\n");

        out.push_str(
            "/// Classify a generic message into its typed representation.\npub fn classify(msg: crate::Message) -> AnyMessage {\n    match msg.msg_type().ok().as_deref().unwrap_or(\"\") {\n",
        );
        for def in by_name.values() {
            writeln!(
                out,
                "        {:?} => AnyMessage::{}(messages::{}::{}(msg)),",
                def.msg_type,
                def.name,
                snake(&def.name),
                def.name
            )
            .unwrap();
        }
        out.push_str("        _ => AnyMessage::Unknown(msg),\n    }\n}\n");
        out
    }
}

fn flatten_members(group: &GroupDef, out: &mut Vec<Tag>) {
    for &t in &group.member_order {
        out.push(t);
        if let Some(nested) = group.groups.get(&t) {
            flatten_members(nested, out);
        }
    }
}