rustyfix-codegen 0.7.4

FIX & FAST (FIX Adapted for STreaming) in pure Rust
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
use heck::{ToPascalCase, ToShoutySnakeCase};
use indoc::formatdoc;
use rustc_hash::FxHashSet;
use rustyfix_dictionary::{self as dict, TagU32};
use smartstring::alias::String as SmartString;

const RUSTYFIX_VERSION: &str = env!("CARGO_PKG_VERSION");

/// Creates a [`String`] that contains a multiline Rust "Doc" comment explaining
/// that all subsequent code was automatically generated.
///
/// The following example is for illustrative purposes only and the actual
/// contents might change. The string is guaranteed not to have any trailing or
/// leading whitespace.
///
/// ```text
/// //! Generated automatically by RustyFix. Do not modify manually.
/// ```
pub fn generated_code_notice() -> SmartString {
    formatdoc!(
        r#"
            // Generated automatically by RustyFix {} on {}.
            //
            // DO NOT MODIFY MANUALLY.
            // DO NOT COMMIT TO VERSION CONTROL.
            // ALL CHANGES WILL BE OVERWRITTEN."#,
        RUSTYFIX_VERSION,
        chrono::Utc::now().to_rfc2822(),
    )
    .into()
}

/// Generates the Rust code for an `enum` that has variants that map 1:1 the
/// available values for `field`.
pub fn codegen_field_type_enum(field: dict::Field, settings: &Settings) -> String {
    let derives = settings.derives_for_allowed_values.join(", ");
    let attributes_str = if settings.attributes_for_allowed_values.is_empty() {
        String::new()
    } else {
        format!("{}\n", settings.attributes_for_allowed_values.join("\n"))
    };
    let mut variant_identifiers = FxHashSet::default();
    let variants = field
        .enums()
        .unwrap()
        .map(|v| codegen_field_type_enum_variant(v, settings, &mut variant_identifiers))
        .collect::<Vec<_>>()
        .join("\n");
    formatdoc!(
        r#"
            /// Field type variants for [`{field_name}`].
            #[derive({derives})]
            #[allow(clippy::enum_variant_names)]
            {attributes}pub enum {identifier} {{
            {variants}
            }}"#,
        field_name = field.name().to_pascal_case(),
        derives = derives,
        attributes = attributes_str,
        identifier = field.name().to_pascal_case(),
        variants = variants,
    )
}

fn codegen_field_type_enum_variant(
    allowed_value: dict::FieldEnum,
    settings: &Settings,
    variant_identifiers: &mut FxHashSet<String>,
) -> SmartString {
    let mut identifier = allowed_value.description().to_pascal_case();
    let original_identifier = identifier.clone();
    let identifier_needs_prefix = !allowed_value
        .description()
        .chars()
        .next()
        .unwrap_or('_')
        .is_ascii_alphabetic();
    if identifier_needs_prefix {
        identifier = format!("_{identifier}");
    }
    // E.g. `TickDirection::PlusTick` -> `TickDirection::Plus`.
    if let Some(s) = identifier.strip_suffix("Tick")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    // E.g. `QuoteCancelType::CancelForSymbol` -> `QuoteCancelType::Symbol`
    if let Some(s) = identifier.strip_prefix("CancelFor")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    // E.g. `SecurityRequestType::RequestSecurityIdentityAndSpecifications`
    if let Some(s) = identifier.strip_prefix("Request")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    // E.g. `MultiLegReportingType::SingleSecurity`
    if let Some(s) = identifier.strip_suffix("Security")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_prefix("RelatedTo")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_suffix("Price")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_prefix("No")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_suffix("Trade")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_prefix("At")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_suffix("Deal")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_suffix("Sale")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_prefix("As")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    if let Some(s) = identifier.strip_prefix("Of")
        && !s.is_empty()
    {
        identifier = s.to_string();
    }
    // Ensure identifier is valid Rust identifier
    let mut final_identifier = identifier.to_pascal_case();
    if final_identifier
        .chars()
        .next()
        .is_none_or(|c| !c.is_ascii_alphabetic())
    {
        final_identifier = format!("_{final_identifier}");
    }

    // Handle duplicates on the final identifier
    if variant_identifiers.contains(&final_identifier) {
        // Fall back to original identifier if there's a collision
        final_identifier = original_identifier.to_pascal_case();
        if final_identifier
            .chars()
            .next()
            .is_none_or(|c| !c.is_ascii_alphabetic())
        {
            final_identifier = format!("_{final_identifier}");
        }

        // If still duplicated, add a suffix
        let mut counter = 2;
        let base_identifier = final_identifier.clone();
        while variant_identifiers.contains(&final_identifier) {
            final_identifier = format!("{base_identifier}{counter}");
            counter += 1;
        }
    }
    variant_identifiers.insert(final_identifier.clone());
    let value_literal = allowed_value.value();
    indent_string(
        formatdoc!(
            r#"
                /// {doc}
                #[rustyfix(variant = "{value_literal}")]
                {identifier},"#,
            doc = format!("Field variant '{}'.", value_literal),
            value_literal = value_literal,
            identifier = final_identifier,
        )
        .as_str(),
        settings.indentation.as_str(),
    )
}

/// Code generation settings. Instantiate with [`Default::default`] and then
/// change field values if necessary.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct Settings {
    /// The indentation prefix of all generated Rust code. Four
    /// spaces by default.
    pub indentation: String,
    /// The base indentation level of all generated Rust code. Zero by default.
    pub indentation_depth: u32,
    /// The name of the `rustyfix` crate for imports. `rustyfix` by default.
    pub rustyfix_crate_name: String,
    /// A list of derive macros on top of all generated FIX datatype `enum`s. E.g.:
    ///
    /// ```
    /// // #[derive(Foobar, Spam)]
    /// enum FoodOrDrink {
    ///     Food,
    ///     Drink,
    /// }
    /// ```
    ///
    /// Contains [`Debug`], [`Copy`], [`Clone`], [`PartialEq`], [`Eq`],
    /// [`Hash`], [`FieldType`](crate::FieldType) by default.
    pub derives_for_allowed_values: Vec<String>,
    /// A list of attribute macros for generated `enum`s variants. E.g.:
    ///
    /// ```
    /// enum FoodOrDrink {
    ///     // #[foobar]
    ///     Food,
    ///     // #[spam]
    ///     Drink,
    /// }
    /// ```
    ///
    /// Empty by default.
    pub attributes_for_allowed_values: Vec<String>,
}

impl Default for Settings {
    fn default() -> Self {
        Self {
            indentation: "    ".to_string(),
            indentation_depth: 0,
            derives_for_allowed_values: vec![
                "Debug".to_string(),
                "Copy".to_string(),
                "Clone".to_string(),
                "PartialEq".to_string(),
                "Eq".to_string(),
                "Hash".to_string(),
                "FieldType".to_string(),
            ],
            attributes_for_allowed_values: vec![],
            rustyfix_crate_name: "rustyfix".to_string(),
        }
    }
}

/// Generates the Rust code for a FIX field definition.
pub fn codegen_field_definition_struct(
    fix_dictionary: &dict::Dictionary,
    field: dict::Field,
) -> String {
    let mut header = FxHashSet::default();
    let mut trailer = FxHashSet::default();
    for item in fix_dictionary
        .component_by_name("StandardHeader")
        .unwrap()
        .items()
    {
        if let dict::LayoutItemKind::Field(f) = item.kind() {
            header.insert(f.tag());
        }
    }
    for item in fix_dictionary
        .component_by_name("StandardTrailer")
        .unwrap()
        .items()
    {
        if let dict::LayoutItemKind::Field(f) = item.kind() {
            trailer.insert(f.tag());
        }
    }
    gen_field_definition_with_hashsets(fix_dictionary, &header, &trailer, field)
}

/// Generates `const` implementors of
/// [`IsFieldDefinition`](super::dict::IsFieldDefinition).
///
/// The generated module will contain:
///
/// - A generated code notice ([generated_code_notice]).
/// - `enum` definitions for FIX field types.
/// - A constant implementor of
///   [`IsFieldDefinition`](super::dict::IsFieldDefinition)
///   for each FIX field.
///
/// The Rust code will be free of any leading and trailing whitespace.
/// An effort is made to provide good formatting, but users shouldn't rely on it
/// and assume that formatting might be bad.
pub fn gen_definitions(fix_dictionary: &dict::Dictionary, settings: &Settings) -> String {
    let enums = fix_dictionary
        .fields()
        .iter()
        .filter(|f| f.enums().is_some())
        .map(|f| codegen_field_type_enum(*f, settings))
        .collect::<Vec<String>>()
        .join("\n\n");
    let field_defs = fix_dictionary
        .fields()
        .iter()
        .map(|field| codegen_field_definition_struct(fix_dictionary, *field))
        .collect::<Vec<String>>()
        .join("\n\n");
    let top_comment = onixs_link_to_dictionary(fix_dictionary.version()).unwrap_or_default();
    let code = formatdoc!(
        r#"
            {notice}

            // {top_comment}

            use {rustyfix_path}::dict::{{FieldLocation, FixDatatype}};
            use {rustyfix_path}::definitions::HardCodedFixFieldDefinition;
            use {rustyfix_path}::FieldType;

            {enum_definitions}

            {field_defs}"#,
        notice = generated_code_notice(),
        top_comment = top_comment,
        enum_definitions = enums,
        field_defs = field_defs,
        rustyfix_path = settings.rustyfix_crate_name,
    );
    code
}

fn indent_string(s: &str, prefix: &str) -> SmartString {
    s.lines()
        .map(|line| format!("{prefix}{line}"))
        .collect::<Vec<String>>()
        .join("\n")
        .into()
}

fn onixs_link_to_field(fix_version: &str, field: dict::Field) -> Option<SmartString> {
    Some(
        format!(
            "https://www.onixs.biz/fix-dictionary/{}/tagnum_{}.html",
            onixs_dictionary_id(fix_version)?,
            field.tag().get()
        )
        .into(),
    )
}

fn onixs_link_to_dictionary(fix_version: &str) -> Option<SmartString> {
    Some(
        format!(
            "https://www.onixs.biz/fix-dictionary/{}/index.html",
            onixs_dictionary_id(fix_version)?
        )
        .into(),
    )
}

fn onixs_dictionary_id(fix_version: &str) -> Option<&str> {
    Some(match fix_version {
        "FIX.4.0" => "4.0",
        "FIX.4.1" => "4.1",
        "FIX.4.2" => "4.2",
        "FIX.4.3" => "4.3",
        "FIX.4.4" => "4.4",
        "FIX.5.0" => "5.0",
        "FIX.5.0-SP1" => "5.0.sp1",
        "FIX.5.0-SP2" => "5.0.sp2",
        "FIXT.1.1" => "fixt1.1",
        _ => return None,
    })
}

fn gen_field_definition_with_hashsets(
    fix_dictionary: &dict::Dictionary,
    header_tags: &FxHashSet<TagU32>,
    trailer_tags: &FxHashSet<TagU32>,
    field: dict::Field,
) -> String {
    let name = field.name().to_shouty_snake_case();
    let tag = field.tag().to_string();
    let field_location = if header_tags.contains(&field.tag()) {
        "Header"
    } else if trailer_tags.contains(&field.tag()) {
        "Trailer"
    } else {
        "Body"
    };
    let doc_link = onixs_link_to_field(fix_dictionary.version(), field);
    let doc = if let Some(doc_link) = doc_link {
        format!("/// Field attributes for [`{name} <{tag}>`]({doc_link}).")
    } else {
        format!("/// Field attributes for `{name} <{tag}>`.")
    };

    formatdoc!(
        r#"
            {doc}
            pub const {identifier}: &HardCodedFixFieldDefinition = &HardCodedFixFieldDefinition {{
                name: "{name}",
                tag: {tag},
                data_type: FixDatatype::{data_type},
                location: FieldLocation::{field_location},
            }};"#,
        doc = doc,
        identifier = name,
        name = field.name(),
        tag = tag,
        field_location = field_location,
        data_type = <&'static str as From<dict::FixDatatype>>::from(field.data_type().basetype()),
    )
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn syntax_of_field_definitions_is_ok() {
        let codegen_settings = Settings::default();
        for dict in dict::Dictionary::common_dictionaries().into_iter() {
            let code = gen_definitions(&dict, &codegen_settings);
            syn::parse_file(code.as_str()).unwrap();
        }
    }

    #[test]
    fn generated_code_notice_is_trimmed() {
        let notice = generated_code_notice();
        assert_eq!(notice, notice.trim());
    }
}