Skip to main content

minifix_codegen/
lib.rs

1use fnv::FnvHashSet;
2use heck::{ToPascalCase, ToShoutySnakeCase};
3use indoc::formatdoc;
4use minifix_dictionary::{self as dict, TagU32};
5
6const MINIFIX_VERSION: &str = env!("CARGO_PKG_VERSION");
7
8/// Creates a [`String`] that contains a multiline Rust "Doc" comment explaining
9/// that all subsequent code was automatically generated.
10///
11/// The following example is for illustrative purposes only and the actual
12/// contents might change. The string is guaranteed not to have any trailing or
13/// leading whitespace.
14///
15/// ```text
16/// //! Generated automatically by miniFIX. Do not modify manually.
17/// ```
18pub fn generated_code_notice() -> String {
19    formatdoc!(
20        r#"
21            // Generated automatically by miniFIX {} on {}.
22            //
23            // DO NOT MODIFY MANUALLY.
24            // DO NOT COMMIT TO VERSION CONTROL.
25            // ALL CHANGES WILL BE OVERWRITTEN."#,
26        MINIFIX_VERSION,
27        chrono::Utc::now().to_rfc2822(),
28    )
29}
30
31/// Generates the Rust code for an `enum` that has variants that map 1:1 the
32/// available values for `field`.
33pub fn codegen_field_type_enum(
34    field: dict::Field,
35    settings: &Settings,
36) -> String {
37    let derives = settings.derives_for_allowed_values.join(", ");
38    let attributes = settings.attributes_for_allowed_values.join("\n");
39    let variants = field
40        .enums()
41        .unwrap()
42        .map(|v| codegen_field_type_enum_variant(v, settings))
43        .collect::<Vec<String>>()
44        .join("\n");
45    formatdoc!(
46        r#"
47            /// Field type variants for [`{field_name}`].
48            #[derive({derives})]
49            {attributes}
50            pub enum {identifier} {{
51            {variants}
52            }}"#,
53        field_name = field.name().to_pascal_case(),
54        derives = derives,
55        attributes = attributes,
56        identifier = field.name().to_pascal_case(),
57        variants = variants,
58    )
59}
60
61fn codegen_field_type_enum_variant(
62    allowed_value: dict::FieldEnum,
63    settings: &Settings,
64) -> String {
65    let mut identifier = allowed_value.description().to_pascal_case();
66    let identifier_needs_prefix = !allowed_value
67        .description()
68        .chars()
69        .next()
70        .unwrap_or('_')
71        .is_ascii_alphabetic();
72    if identifier_needs_prefix {
73        identifier = format!("_{identifier}");
74    }
75    let value_literal = allowed_value.value();
76    indent_string(
77        formatdoc!(
78            r#"
79                /// {doc}
80                #[minifix(variant = "{value_literal}")]
81                {identifier},"#,
82            doc = format!("Field variant '{}'.", value_literal),
83            value_literal = value_literal,
84            identifier = identifier,
85        )
86        .as_str(),
87        settings.indentation.as_str(),
88    )
89}
90
91/// Code generation settings. Instantiate with [`Default::default`] and then
92/// change field values if necessary.
93#[derive(Debug, Clone)]
94#[non_exhaustive]
95pub struct Settings {
96    /// The indentation prefix of all generated Rust code. Four
97    /// spaces by default.
98    pub indentation: String,
99    /// The base indentation level of all generated Rust code. Zero by default.
100    pub indentation_depth: u32,
101    /// The name of the `minifix` crate for imports. `minifix` by default.
102    pub minifix_crate_name: String,
103    /// A list of derive macros on top of all generated FIX datatype `enum`s. E.g.:
104    ///
105    /// ```
106    /// // #[derive(Foobar, Spam)]
107    /// enum FoodOrDrink {
108    ///     Food,
109    ///     Drink,
110    /// }
111    /// ```
112    ///
113    /// Contains [`Debug`], [`Copy`], [`Clone`], [`PartialEq`], [`Eq`],
114    /// [`Hash`], [`FieldType`](crate::FieldType) by default.
115    pub derives_for_allowed_values: Vec<String>,
116    /// A list of attribute macros for generated `enum`s variants. E.g.:
117    ///
118    /// ```
119    /// enum FoodOrDrink {
120    ///     // #[foobar]
121    ///     Food,
122    ///     // #[spam]
123    ///     Drink,
124    /// }
125    /// ```
126    ///
127    /// Empty by default.
128    pub attributes_for_allowed_values: Vec<String>,
129}
130
131impl Default for Settings {
132    fn default() -> Self {
133        Self {
134            indentation: "    ".to_string(),
135            indentation_depth: 0,
136            derives_for_allowed_values: vec![
137                "Debug".to_string(),
138                "Copy".to_string(),
139                "Clone".to_string(),
140                "PartialEq".to_string(),
141                "Eq".to_string(),
142                "Hash".to_string(),
143                "FieldType".to_string(),
144            ],
145            attributes_for_allowed_values: vec![],
146            minifix_crate_name: "minifix".to_string(),
147        }
148    }
149}
150
151/// Generates the Rust code for a FIX field definition.
152pub fn codegen_field_definition_struct(
153    fix_dictionary: &dict::Dictionary,
154    field: dict::Field,
155) -> String {
156    let mut header = FnvHashSet::default();
157    let mut trailer = FnvHashSet::default();
158    for item in
159        fix_dictionary.component_by_name("StandardHeader").unwrap().items()
160    {
161        if let dict::LayoutItemKind::Field(f) = item.kind() {
162            header.insert(f.tag());
163        }
164    }
165    for item in
166        fix_dictionary.component_by_name("StandardTrailer").unwrap().items()
167    {
168        if let dict::LayoutItemKind::Field(f) = item.kind() {
169            trailer.insert(f.tag());
170        }
171    }
172    gen_field_definition_with_hashsets(
173        fix_dictionary,
174        &header,
175        &trailer,
176        field,
177    )
178}
179
180/// Generates `const` implementors of
181/// [`IsFieldDefinition`](super::dict::IsFieldDefinition).
182///
183/// The generated module will contain:
184///
185/// - A generated code notice ([generated_code_notice]).
186/// - `enum` definitions for FIX field types.
187/// - A constant implementor of
188///   [`IsFieldDefinition`](super::dict::IsFieldDefinition)
189///   for each FIX field.
190///
191/// The Rust code will be free of any leading and trailing whitespace.
192/// An effort is made to provide good formatting, but users shouldn't rely on it
193/// and assume that formatting might be bad.
194pub fn gen_definitions(
195    fix_dictionary: &dict::Dictionary,
196    settings: &Settings,
197) -> String {
198    let enums = fix_dictionary
199        .fields()
200        .iter()
201        .filter(|f| f.enums().is_some())
202        .map(|f| codegen_field_type_enum(*f, settings))
203        .collect::<Vec<String>>()
204        .join("\n\n");
205    let field_defs = fix_dictionary
206        .fields()
207        .iter()
208        .map(|field| codegen_field_definition_struct(fix_dictionary, *field))
209        .collect::<Vec<String>>()
210        .join("\n\n");
211    let top_comment =
212        onixs_link_to_dictionary(fix_dictionary.version()).unwrap_or_default();
213    let code = formatdoc!(
214        r#"
215            {notice}
216
217            // {top_comment}
218
219            use {minifix_path}::dict::{{FieldLocation, FixDatatype}};
220            use {minifix_path}::definitions::HardCodedFixFieldDefinition;
221            use {minifix_path}::FieldType;
222
223            {enum_definitions}
224
225            {field_defs}"#,
226        notice = generated_code_notice(),
227        top_comment = top_comment,
228        enum_definitions = enums,
229        field_defs = field_defs,
230        minifix_path = settings.minifix_crate_name,
231    );
232    code
233}
234
235fn indent_string(s: &str, prefix: &str) -> String {
236    s.lines()
237        .map(|line| format!("{prefix}{line}"))
238        .collect::<Vec<String>>()
239        .join("\n")
240}
241
242fn onixs_link_to_field(
243    fix_version: &str,
244    field: dict::Field,
245) -> Option<String> {
246    Some(format!(
247        "https://www.onixs.biz/fix-dictionary/{}/tagnum_{}.html",
248        onixs_dictionary_id(fix_version)?,
249        field.tag().get()
250    ))
251}
252
253fn onixs_link_to_dictionary(fix_version: &str) -> Option<String> {
254    Some(format!(
255        "https://www.onixs.biz/fix-dictionary/{}/index.html",
256        onixs_dictionary_id(fix_version)?
257    ))
258}
259
260fn onixs_dictionary_id(fix_version: &str) -> Option<&str> {
261    Some(match fix_version {
262        "FIX.4.0" => "4.0",
263        "FIX.4.1" => "4.1",
264        "FIX.4.2" => "4.2",
265        "FIX.4.3" => "4.3",
266        "FIX.4.4" => "4.4",
267        "FIXT.1.1" => "fixt1.1",
268        _ => return None,
269    })
270}
271
272fn gen_field_definition_with_hashsets(
273    fix_dictionary: &dict::Dictionary,
274    header_tags: &FnvHashSet<TagU32>,
275    trailer_tags: &FnvHashSet<TagU32>,
276    field: dict::Field,
277) -> String {
278    let name = field.name().to_shouty_snake_case();
279    let tag = field.tag().to_string();
280    let field_location = if header_tags.contains(&field.tag()) {
281        "Header"
282    } else if trailer_tags.contains(&field.tag()) {
283        "Trailer"
284    } else {
285        "Body"
286    };
287    let doc_link = onixs_link_to_field(fix_dictionary.version(), field);
288    let doc = if let Some(doc_link) = doc_link {
289        format!("/// Field attributes for [`{name} <{tag}>`]({doc_link}).")
290    } else {
291        format!("/// Field attributes for `{name} <{tag}>`.")
292    };
293
294    formatdoc!(
295        r#"
296            {doc}
297            pub const {identifier}: &HardCodedFixFieldDefinition = &HardCodedFixFieldDefinition {{
298                name: "{name}",
299                tag: {tag},
300                data_type: FixDatatype::{data_type},
301                location: FieldLocation::{field_location},
302            }};"#,
303        doc = doc,
304        identifier = name,
305        name = field.name(),
306        tag = tag,
307        field_location = field_location,
308        data_type = <&'static str as From<dict::FixDatatype>>::from(
309            field.data_type().basetype()
310        ),
311    )
312}
313
314#[cfg(test)]
315mod test {
316    use super::*;
317
318    #[test]
319    fn syntax_of_field_definitions_is_ok() {
320        let codegen_settings = Settings::default();
321        for dict in dict::Dictionary::common_dictionaries().into_iter() {
322            let code = gen_definitions(&dict, &codegen_settings);
323            syn::parse_file(code.as_str()).unwrap();
324        }
325    }
326
327    #[test]
328    fn generated_code_notice_is_trimmed() {
329        let notice = generated_code_notice();
330        assert_eq!(notice, notice.trim());
331    }
332}