Skip to main content

refix_codegen/
rust.rs

1mod components;
2mod dialect;
3mod dispatch;
4mod docs;
5mod enums;
6mod error;
7mod groups;
8mod layout;
9mod messages;
10mod modules;
11mod names;
12mod naming;
13mod printing;
14mod views;
15mod warm_up;
16
17use std::path::{Path, PathBuf};
18
19use refix_dictionary::Dictionary;
20
21use crate::components::components;
22use crate::conversion::{Conversion, unclaimed_types};
23use crate::dialect::length_tags;
24use crate::envelope::Envelope;
25use crate::groups::instance_context;
26use crate::namespace::Owner;
27use crate::package::MARKER;
28use crate::{Module, Package};
29use components::emit_component;
30use dialect::emit_dialect;
31use dispatch::emit_dispatch;
32use enums::emit_enum;
33pub use error::Error;
34use groups::{emit_group, shared_groups};
35use messages::emit_message;
36use modules::{File, Folder, Modules, UNUSED, Uses, emit_folder, emit_imports, emit_use};
37use names::Names;
38use views::emit_view;
39use warm_up::emit_warm_up;
40
41/// The module tree's files.
42///
43/// The root file offers every type and reads a raw message as its type. The
44/// enums share a file. Every message has a file in `messages` and every
45/// other type has one in `components`, where a group declared in a type
46/// stays with it. Only the root's names are public.
47pub fn generate(dictionary: &Dictionary, source: &str) -> Result<Package, Error> {
48    let mut warnings = Vec::new();
49    let names = Names::new(dictionary, &mut warnings)?;
50    let envelope = Envelope::of(dictionary);
51
52    let enums: Vec<String> = dictionary
53        .fields()
54        .iter()
55        .filter(|field| Conversion::of(field).is_enum())
56        .map(|field| emit_enum(field, &names))
57        .collect();
58    let components = component_files(dictionary, &envelope, &names);
59    let messages: Vec<File> = dictionary
60        .messages()
61        .map(|message| File {
62            name: message.name().to_owned(),
63            owner: Owner::Message(message.name().to_owned()),
64            code: emit_message(message, &envelope, &names),
65            uses: Uses::of_message(message, &envelope, &names),
66        })
67        .collect();
68
69    // The layout is the emitter's own, so rustfmt leaves it alone. That keeps
70    // the output byte-stable across rustfmt versions.
71    let header =
72        format!("// {MARKER} from {source}. Do not edit.\n#![cfg_attr(rustfmt, rustfmt::skip)]\n");
73    let mut modules = Vec::new();
74    let mut children = Vec::new();
75    for (folder, files) in [
76        (Folder::Components, &components),
77        (Folder::Messages, &messages),
78    ] {
79        if files.is_empty() {
80            continue;
81        }
82        let homes = Modules::new(files)?;
83        let directory = Path::new(folder.name());
84        modules.push(Module {
85            path: directory.join("mod.rs"),
86            code: format!("{header}\n{}", emit_folder(files, &homes)),
87        });
88        modules.extend(files.iter().map(|file| Module {
89            path: directory.join(format!("{}.rs", homes.of(&file.name))),
90            code: format!(
91                "{header}\n{}\n{}",
92                emit_imports(&file.uses, folder),
93                file.code
94            ),
95        }));
96        children.push(folder.name());
97    }
98    if !enums.is_empty() {
99        modules.push(Module {
100            path: PathBuf::from("enums.rs"),
101            code: format!("{header}\n{}", enums.join("\n")),
102        });
103        children.push("enums");
104    }
105    children.sort_unstable();
106    let sections = [emit_root_imports(dictionary), emit_children(&children)]
107        .into_iter()
108        .filter(|section| !section.is_empty())
109        .chain([emit_dialect(dictionary)])
110        .chain(emit_dispatch(dictionary))
111        .chain(emit_warm_up(dictionary, &envelope, &names))
112        .collect::<Vec<String>>()
113        .join("\n");
114    modules.insert(
115        0,
116        Module {
117            path: PathBuf::from("mod.rs"),
118            code: format!("{header}\n{sections}"),
119        },
120    );
121
122    warnings.extend(unclaimed_types(dictionary));
123    Ok(Package::new(
124        modules,
125        warnings,
126        &["", Folder::Components.name(), Folder::Messages.name()],
127    ))
128}
129
130/// The files in `components`, which hold the shared groups, the components
131/// and the header and trailer views.
132fn component_files(dictionary: &Dictionary, envelope: &Envelope, names: &Names) -> Vec<File> {
133    let groups = shared_groups(dictionary).into_iter().map(|group| File {
134        name: names.group_type(group).to_owned(),
135        owner: Owner::Group(instance_context(group)),
136        code: emit_group(group, names),
137        uses: Uses::of_group(group, names),
138    });
139    let components = components(dictionary).into_iter().map(|component| File {
140        name: component.name().to_owned(),
141        owner: Owner::Component(component.name().to_owned()),
142        code: emit_component(component, names),
143        uses: Uses::of_component(component, names),
144    });
145    let views = envelope.sections.iter().map(|section| File {
146        name: section.type_name().to_owned(),
147        owner: Owner::Generated,
148        code: emit_view(*section, dictionary, envelope, names),
149        uses: Uses::of_view(*section, dictionary, envelope, names),
150    });
151    groups.chain(components).chain(views).collect()
152}
153
154/// What the root file's own items name from `refix_message`.
155fn emit_root_imports(dictionary: &Dictionary) -> String {
156    let has_messages = dictionary.messages().next().is_some();
157    let mut imports = vec!["Dialect"];
158    if has_messages {
159        imports.push("RawMessage");
160    }
161    if has_messages || !length_tags(dictionary).is_empty() {
162        imports.push("Tag");
163    }
164    emit_use("use", "refix_message", &imports)
165}
166
167/// The root's child modules, private, with everything in them offered from
168/// the root.
169fn emit_children(children: &[&str]) -> String {
170    if children.is_empty() {
171        return String::new();
172    }
173    let declarations: String = children
174        .iter()
175        .map(|child| format!("mod {child};\n"))
176        .collect();
177    let everything: Vec<String> = children.iter().map(|child| format!("{child}::*")).collect();
178    let everything: Vec<&str> = everything.iter().map(String::as_str).collect();
179    format!(
180        "{declarations}\n{UNUSED}{}",
181        emit_use("pub use", "self", &everything)
182    )
183}
184
185#[cfg(test)]
186mod tests {
187    use super::*;
188    use crate::Warning;
189    use refix_dictionary::Tag;
190    use refix_dictionary::spec::{
191        Category, DataType, EnumValue, Field, FieldRef, Group, Member, Message, Protocol, Spec,
192        Version,
193    };
194
195    fn field(name: &str, tag: u32, data_type: DataType) -> Field {
196        Field {
197            name: name.to_owned(),
198            tag: Tag(tag),
199            data_type,
200            length_tag: None,
201            values: vec![],
202        }
203    }
204
205    /// Every file's code, each under a line naming its path.
206    fn listing(package: &Package) -> String {
207        package
208            .modules
209            .iter()
210            .map(|module| format!("=== {}\n{}", module.path.display(), module.code))
211            .collect()
212    }
213
214    fn package_of(spec: Spec) -> Package {
215        generate(&spec.resolve().unwrap().dictionary, "toy.xml").unwrap()
216    }
217
218    fn code_of(spec: Spec) -> String {
219        listing(&package_of(spec))
220    }
221
222    /// The code of the file at `path`.
223    fn file<'a>(package: &'a Package, path: &str) -> &'a str {
224        let module = package
225            .modules
226            .iter()
227            .find(|module| module.path == Path::new(path));
228        &module.unwrap().code
229    }
230
231    fn spec_of(messages: Vec<Message>, fields: Vec<Field>) -> Spec {
232        Spec {
233            version: Version {
234                protocol: Protocol::Fix,
235                major: 4,
236                minor: 4,
237                service_pack: 0,
238            },
239            header: vec![],
240            trailer: vec![],
241            messages,
242            components: vec![],
243            fields,
244        }
245    }
246
247    #[test]
248    fn generates_a_complete_module_tree() {
249        let mut ord_type = field("OrdType", 40, DataType::Char);
250        ord_type.values = vec![
251            EnumValue {
252                value: "1".to_owned(),
253                description: "MARKET".to_owned(),
254            },
255            EnumValue {
256                value: "2".to_owned(),
257                description: "LIMIT".to_owned(),
258            },
259        ];
260        let spec = spec_of(
261            vec![Message {
262                name: "NewOrderSingle".to_owned(),
263                msg_type: "D".to_owned(),
264                members: vec![
265                    Member::Field(FieldRef {
266                        tag: Tag(11),
267                        is_required: true,
268                    }),
269                    Member::Field(FieldRef {
270                        tag: Tag(38),
271                        is_required: false,
272                    }),
273                    Member::Field(FieldRef {
274                        tag: Tag(44),
275                        is_required: false,
276                    }),
277                    Member::Field(FieldRef {
278                        tag: Tag(40),
279                        is_required: false,
280                    }),
281                ],
282                category: Category::App,
283            }],
284            vec![
285                field("ClOrdID", 11, DataType::String),
286                field("OrderQty", 38, DataType::Int),
287                field("Price", 44, DataType::Other("PRICE".to_owned())),
288                ord_type,
289            ],
290        );
291
292        let expected = r#"=== mod.rs
293// @generated by refix codegen from toy.xml. Do not edit.
294#![cfg_attr(rustfmt, rustfmt::skip)]
295
296use refix_message::{Dialect, RawMessage, Tag};
297
298mod enums;
299mod messages;
300
301#[allow(unused_imports)]
302pub use self::{enums::*, messages::*};
303
304/// The dialect of this dictionary.
305pub const DIALECT: Dialect<'static> = Dialect::new();
306
307/// A message read as the type its MsgType names.
308pub enum Message {
309    NewOrderSingle(NewOrderSingle),
310    Unrecognized(RawMessage),
311}
312
313impl Message {
314    pub fn from_raw(raw: RawMessage) -> Self {
315        match raw.get(Tag(35)) {
316            Some(NewOrderSingle::MSG_TYPE) => Self::NewOrderSingle(NewOrderSingle::from_raw(raw)),
317            _ => Self::Unrecognized(raw),
318        }
319    }
320}
321
322impl std::fmt::Debug for Message {
323    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324        match self {
325            Self::NewOrderSingle(message) => std::fmt::Debug::fmt(message, f),
326            Self::Unrecognized(raw) => write!(f, "Unrecognized({raw})"),
327        }
328    }
329}
330
331impl std::fmt::Display for Message {
332    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
333        match self {
334            Self::NewOrderSingle(message) => std::fmt::Display::fmt(message, f),
335            Self::Unrecognized(raw) => std::fmt::Display::fmt(raw, f),
336        }
337    }
338}
339=== messages/mod.rs
340// @generated by refix codegen from toy.xml. Do not edit.
341#![cfg_attr(rustfmt, rustfmt::skip)]
342
343mod new_order_single;
344
345#[allow(unused_imports)]
346pub use self::{
347    new_order_single::NewOrderSingle,
348};
349=== messages/new_order_single.rs
350// @generated by refix codegen from toy.xml. Do not edit.
351#![cfg_attr(rustfmt, rustfmt::skip)]
352
353use refix_message::{InvalidValue, RawMessage, Tag};
354
355use super::super::enums::OrdType;
356
357/// The `NewOrderSingle` (35=D) message.
358pub struct NewOrderSingle(RawMessage);
359
360impl NewOrderSingle {
361    pub const MSG_TYPE: &[u8] = b"D";
362
363    pub fn from_raw(raw: RawMessage) -> Self {
364        Self(raw)
365    }
366
367    pub fn raw(&self) -> &RawMessage {
368        &self.0
369    }
370
371    /// The `ClOrdID` (11) field.
372    #[doc(alias = "ClOrdID")]
373    pub fn cl_ord_id(&self) -> Result<Option<&str>, InvalidValue> {
374        self.0.get_str(Tag(11))
375    }
376
377    /// The `OrderQty` (38) field.
378    #[doc(alias = "OrderQty")]
379    pub fn order_qty(&self) -> Result<Option<i64>, InvalidValue> {
380        self.0.get_int(Tag(38))
381    }
382
383    /// The `Price` (44) field.
384    #[doc(alias = "Price")]
385    pub fn price_raw(&self) -> Option<&[u8]> {
386        self.0.get(Tag(44))
387    }
388
389    /// The `OrdType` (40) field.
390    #[doc(alias = "OrdType")]
391    pub fn ord_type(&self) -> Result<Option<OrdType<'_>>, InvalidValue> {
392        Ok(self.0.get_str(Tag(40))?.map(OrdType::from_value))
393    }
394}
395
396impl std::fmt::Debug for NewOrderSingle {
397    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
398        write!(f, "NewOrderSingle({})", self.0)
399    }
400}
401
402impl std::fmt::Display for NewOrderSingle {
403    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
404        std::fmt::Display::fmt(&self.0, f)
405    }
406}
407=== enums.rs
408// @generated by refix codegen from toy.xml. Do not edit.
409#![cfg_attr(rustfmt, rustfmt::skip)]
410
411/// The values of the `OrdType` (40) field.
412#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
413pub enum OrdType<'a> {
414    /// `1`
415    Market,
416    /// `2`
417    Limit,
418    /// A value the dictionary does not list.
419    Unrecognized(&'a str),
420}
421
422impl<'a> OrdType<'a> {
423    pub fn from_value(value: &'a str) -> Self {
424        match value {
425            "1" => Self::Market,
426            "2" => Self::Limit,
427            unrecognized => Self::Unrecognized(unrecognized),
428        }
429    }
430
431    pub fn value(self) -> &'a str {
432        match self {
433            Self::Market => "1",
434            Self::Limit => "2",
435            Self::Unrecognized(value) => value,
436        }
437    }
438}
439
440impl<'a> From<&'a str> for OrdType<'a> {
441    fn from(value: &'a str) -> Self {
442        Self::from_value(value)
443    }
444}
445"#;
446
447        let generated = package_of(spec);
448        assert_eq!(listing(&generated), expected);
449        assert_eq!(
450            generated.warnings,
451            [Warning::UnclaimedType {
452                field: "Price".to_owned(),
453                data_type: DataType::Other("PRICE".to_owned()),
454            }]
455        );
456    }
457
458    #[test]
459    fn a_dictionary_without_types_is_one_file() {
460        let package = package_of(spec_of(vec![], vec![]));
461
462        assert_eq!(
463            listing(&package),
464            r#"=== mod.rs
465// @generated by refix codegen from toy.xml. Do not edit.
466#![cfg_attr(rustfmt, rustfmt::skip)]
467
468use refix_message::Dialect;
469
470/// The dialect of this dictionary.
471pub const DIALECT: Dialect<'static> = Dialect::new();
472"#
473        );
474    }
475
476    #[test]
477    fn two_types_needing_one_file_are_an_error() {
478        let message = |name: &str, msg_type: &str| Message {
479            name: name.to_owned(),
480            msg_type: msg_type.to_owned(),
481            members: vec![],
482            category: Category::App,
483        };
484        let spec = spec_of(
485            vec![message("QuoteID", "a"), message("QuoteId", "b")],
486            vec![],
487        );
488
489        let error = generate(&spec.resolve().unwrap().dictionary, "toy.xml").unwrap_err();
490
491        assert_eq!(
492            error.to_string(),
493            "rust module `quote_id` is taken by both message 'QuoteID' and message 'QuoteId'"
494        );
495    }
496
497    #[test]
498    fn a_dictionary_without_messages_has_no_message_enum() {
499        let spec = spec_of(vec![], vec![]);
500
501        let code = code_of(spec);
502
503        assert!(!code.contains("pub enum Message"));
504    }
505
506    #[test]
507    fn the_dialect_lists_every_linked_length_tag_in_order() {
508        let spec = spec_of(
509            vec![],
510            vec![
511                field("VenueDataLen", 5001, DataType::Length),
512                Field {
513                    length_tag: Some(Tag(5001)),
514                    ..field("VenueData", 5002, DataType::Data)
515                },
516                field("RawDataLength", 95, DataType::Length),
517                Field {
518                    length_tag: Some(Tag(95)),
519                    ..field("RawData", 96, DataType::Data)
520                },
521            ],
522        );
523
524        let code = code_of(spec);
525
526        assert!(code.contains(
527            "pub const DIALECT: Dialect<'static> = Dialect::new().with_extra_length_tags(&[Tag(95), Tag(5001)]);\n"
528        ));
529    }
530
531    #[test]
532    fn a_file_imports_multiple_values_only_when_it_reads_them() {
533        let mut exec_inst = field("ExecInst", 18, DataType::MultipleStringValue);
534        exec_inst.values = vec![EnumValue {
535            value: "1".to_owned(),
536            description: "NOT_HELD".to_owned(),
537        }];
538        let order = |members| Message {
539            name: "NewOrderSingle".to_owned(),
540            msg_type: "D".to_owned(),
541            members,
542            category: Category::App,
543        };
544        let reads = spec_of(
545            vec![order(vec![Member::Field(FieldRef {
546                tag: Tag(18),
547                is_required: false,
548            })])],
549            vec![exec_inst.clone()],
550        );
551        let unused = spec_of(vec![order(vec![])], vec![exec_inst]);
552
553        let imports = |spec: Spec| {
554            let package = package_of(spec);
555            let code = file(&package, "messages/new_order_single.rs");
556            code.lines()
557                .find(|line| line.starts_with("use "))
558                .unwrap()
559                .to_owned()
560        };
561
562        assert_eq!(
563            imports(reads),
564            "use refix_message::{InvalidValue, MultipleValues, RawMessage, Tag};"
565        );
566        assert_eq!(imports(unused), "use refix_message::RawMessage;");
567    }
568
569    #[test]
570    fn a_file_imports_a_value_type_only_when_it_reads_one() {
571        let order = |members| Message {
572            name: "NewOrderSingle".to_owned(),
573            msg_type: "D".to_owned(),
574            members,
575            category: Category::App,
576        };
577        let imports = |spec: Spec| {
578            let package = package_of(spec);
579            let code = file(&package, "messages/new_order_single.rs");
580            code.lines()
581                .find(|line| line.starts_with("use "))
582                .unwrap()
583                .to_owned()
584        };
585
586        for (value, expected) in [
587            (
588                field("Price", 44, DataType::Price),
589                "use refix_message::{Decimal, InvalidValue, RawMessage, Tag};",
590            ),
591            (
592                field("SettlDate", 64, DataType::LocalMktDate),
593                "use refix_message::{Date, InvalidValue, RawMessage, Tag};",
594            ),
595            (
596                field("MaturityMonthYear", 200, DataType::MonthYear),
597                "use refix_message::{InvalidValue, MonthYear, RawMessage, Tag};",
598            ),
599            (
600                field("MDEntryTime", 273, DataType::UtcTimeOnly),
601                "use refix_message::{InvalidValue, RawMessage, Tag, Time};",
602            ),
603            (
604                field("TransactTime", 60, DataType::UtcTimestamp),
605                "use refix_message::{InvalidValue, RawMessage, Tag, UtcTimestamp};",
606            ),
607            (
608                field("DeskOrderHandlingInst", 1035, DataType::MultipleStringValue),
609                "use refix_message::{InvalidValue, MultipleValues, RawMessage, Tag};",
610            ),
611        ] {
612            let reads = spec_of(
613                vec![order(vec![Member::Field(FieldRef {
614                    tag: value.tag,
615                    is_required: false,
616                })])],
617                vec![value.clone()],
618            );
619            let unused = spec_of(vec![order(vec![])], vec![value]);
620
621            assert_eq!(imports(reads), expected);
622            assert_eq!(imports(unused), "use refix_message::RawMessage;");
623        }
624    }
625
626    #[test]
627    fn a_boolean_reads_as_a_bool_without_an_enum() {
628        let mut locate_reqd = field("LocateReqd", 114, DataType::Boolean);
629        locate_reqd.values = [("Y", "YES"), ("N", "NO")]
630            .map(|(value, description)| EnumValue {
631                value: value.to_owned(),
632                description: description.to_owned(),
633            })
634            .to_vec();
635        let spec = spec_of(
636            vec![Message {
637                name: "NewOrderSingle".to_owned(),
638                msg_type: "D".to_owned(),
639                members: vec![Member::Field(FieldRef {
640                    tag: Tag(114),
641                    is_required: false,
642                })],
643                category: Category::App,
644            }],
645            vec![locate_reqd],
646        );
647
648        let code = code_of(spec);
649
650        assert!(code.contains("pub fn locate_reqd(&self) -> Result<Option<bool>, InvalidValue> {"));
651        assert!(!code.contains("enum LocateReqd"));
652    }
653
654    #[test]
655    fn an_enum_named_like_a_message_is_renamed_with_a_warning() {
656        let mut security_status = field("SecurityStatus", 965, DataType::String);
657        security_status.values = vec![EnumValue {
658            value: "1".to_owned(),
659            description: "ACTIVE".to_owned(),
660        }];
661        let spec = spec_of(
662            vec![Message {
663                name: "SecurityStatus".to_owned(),
664                msg_type: "f".to_owned(),
665                members: vec![Member::Field(FieldRef {
666                    tag: Tag(965),
667                    is_required: false,
668                })],
669                category: Category::App,
670            }],
671            vec![security_status],
672        );
673
674        let generated = package_of(spec);
675
676        assert!(listing(&generated).contains("pub enum SecurityStatusEnum<'a> {"));
677        assert!(listing(&generated).contains("pub struct SecurityStatus(RawMessage);"));
678        assert!(
679            listing(&generated).contains("Result<Option<SecurityStatusEnum<'_>>, InvalidValue>")
680        );
681        assert!(matches!(
682            generated.warnings.as_slice(),
683            [Warning::Renamed { .. }]
684        ));
685    }
686
687    #[test]
688    fn the_message_enum_lists_messages_in_spec_order() {
689        let spec = spec_of(
690            vec![
691                Message {
692                    name: "Heartbeat".to_owned(),
693                    msg_type: "0".to_owned(),
694                    members: vec![],
695                    category: Category::Admin,
696                },
697                Message {
698                    name: "TestRequest".to_owned(),
699                    msg_type: "1".to_owned(),
700                    members: vec![],
701                    category: Category::Admin,
702                },
703            ],
704            vec![],
705        );
706
707        let package = package_of(spec);
708
709        assert!(file(&package, "mod.rs").contains(
710            "pub enum Message {\n    Heartbeat(Heartbeat),\n    TestRequest(TestRequest),\n"
711        ));
712    }
713
714    mod groups {
715        use super::*;
716        use refix_dictionary::spec::{Component, ComponentRef};
717
718        fn field_ref(tag: u32) -> Member {
719            Member::Field(FieldRef {
720                tag: Tag(tag),
721                is_required: false,
722            })
723        }
724
725        fn component_ref(name: &str) -> Member {
726            Member::Component(ComponentRef {
727                name: name.to_owned(),
728                is_required: false,
729            })
730        }
731
732        fn group(count_tag: u32, members: Vec<Member>) -> Member {
733            Member::Group(Group {
734                count_tag: Tag(count_tag),
735                is_required: false,
736                members,
737            })
738        }
739
740        fn message(name: &str, msg_type: &str, members: Vec<Member>) -> Message {
741            Message {
742                name: name.to_owned(),
743                msg_type: msg_type.to_owned(),
744                members,
745                category: Category::App,
746            }
747        }
748
749        /// A spec with `Parties` and its nested `PtysSubGrp`, as FIX44
750        /// declares them, used by `messages`.
751        fn parties_spec(messages: Vec<Message>) -> Spec {
752            let mut spec = spec_of(
753                messages,
754                vec![
755                    field("NoPartyIDs", 453, DataType::NumInGroup),
756                    field("PartyID", 448, DataType::String),
757                    field("NoPartySubIDs", 802, DataType::NumInGroup),
758                    field("PartySubID", 523, DataType::String),
759                ],
760            );
761            spec.components = vec![
762                Component {
763                    name: "Parties".to_owned(),
764                    members: vec![group(
765                        453,
766                        vec![field_ref(448), component_ref("PtysSubGrp")],
767                    )],
768                },
769                Component {
770                    name: "PtysSubGrp".to_owned(),
771                    members: vec![group(802, vec![field_ref(523)])],
772                },
773            ];
774            spec
775        }
776
777        #[test]
778        fn generates_a_type_per_group() {
779            let spec = parties_spec(vec![message(
780                "NewOrderSingle",
781                "D",
782                vec![component_ref("Parties")],
783            )]);
784
785            let expected = r#"=== mod.rs
786// @generated by refix codegen from toy.xml. Do not edit.
787#![cfg_attr(rustfmt, rustfmt::skip)]
788
789use refix_message::{Dialect, RawMessage, Tag};
790
791mod components;
792mod messages;
793
794#[allow(unused_imports)]
795pub use self::{components::*, messages::*};
796
797/// The dialect of this dictionary.
798pub const DIALECT: Dialect<'static> = Dialect::new();
799
800/// A message read as the type its MsgType names.
801pub enum Message {
802    NewOrderSingle(NewOrderSingle),
803    Unrecognized(RawMessage),
804}
805
806impl Message {
807    pub fn from_raw(raw: RawMessage) -> Self {
808        match raw.get(Tag(35)) {
809            Some(NewOrderSingle::MSG_TYPE) => Self::NewOrderSingle(NewOrderSingle::from_raw(raw)),
810            _ => Self::Unrecognized(raw),
811        }
812    }
813}
814
815impl std::fmt::Debug for Message {
816    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
817        match self {
818            Self::NewOrderSingle(message) => std::fmt::Debug::fmt(message, f),
819            Self::Unrecognized(raw) => write!(f, "Unrecognized({raw})"),
820        }
821    }
822}
823
824impl std::fmt::Display for Message {
825    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826        match self {
827            Self::NewOrderSingle(message) => std::fmt::Display::fmt(message, f),
828            Self::Unrecognized(raw) => std::fmt::Display::fmt(raw, f),
829        }
830    }
831}
832
833/// Builds the tag lists that group reads share.
834///
835/// Each list is otherwise built by the first read that needs it. Call this
836/// once at startup to keep that work out of the first messages.
837pub fn warm_up() {
838    Parties::known_tags().get();
839    PtysSubGrp::known_tags().get();
840    NewOrderSingle::known_tags().get();
841}
842=== components/mod.rs
843// @generated by refix codegen from toy.xml. Do not edit.
844#![cfg_attr(rustfmt, rustfmt::skip)]
845
846mod parties;
847mod ptys_sub_grp;
848
849#[allow(unused_imports)]
850pub use self::{
851    parties::Parties,
852    ptys_sub_grp::PtysSubGrp,
853};
854=== components/parties.rs
855// @generated by refix codegen from toy.xml. Do not edit.
856#![cfg_attr(rustfmt, rustfmt::skip)]
857
858use refix_message::{GroupTable, Instances, InvalidValue, LazyKnownTags, Tag};
859
860use super::PtysSubGrp;
861
862/// An instance of the `NoPartyIDs` (453) group.
863#[derive(Clone, Copy)]
864pub struct Parties<'a>(refix_message::Scope<'a>);
865
866impl<'a> From<refix_message::Scope<'a>> for Parties<'a> {
867    fn from(scope: refix_message::Scope<'a>) -> Self {
868        Self(scope)
869    }
870}
871
872impl<'a> Parties<'a> {
873    pub(in super::super) const TABLE: GroupTable<'static> = GroupTable::new(
874        Tag(453),
875        Tag(448),
876        &[Tag(448), Tag(802)],
877        &[PtysSubGrp::TABLE],
878    );
879
880    pub(in super::super) const fn known_tags() -> &'static LazyKnownTags {
881        static TAGS: LazyKnownTags = LazyKnownTags::new(
882            &[Tag(448), Tag(802)],
883            &[PtysSubGrp::known_tags()],
884        );
885        &TAGS
886    }
887
888    pub fn raw(&self) -> refix_message::Scope<'a> {
889        self.0
890    }
891
892    /// The `PartyID` (448) field.
893    #[doc(alias = "PartyID")]
894    pub fn party_id(&self) -> Result<Option<&'a str>, InvalidValue> {
895        self.0.get_str(Tag(448))
896    }
897
898    /// The instances of the `NoPartySubIDs` (802) group.
899    #[doc(alias = "NoPartySubIDs")]
900    pub fn party_sub_ids(&self) -> Result<Instances<'a, PtysSubGrp<'a>>, InvalidValue> {
901        self.0.get_group(&PtysSubGrp::TABLE, &Self::known_tags().get()).map(Instances::from)
902    }
903}
904
905impl std::fmt::Debug for Parties<'_> {
906    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
907        write!(f, "Parties({})", self.0)
908    }
909}
910=== components/ptys_sub_grp.rs
911// @generated by refix codegen from toy.xml. Do not edit.
912#![cfg_attr(rustfmt, rustfmt::skip)]
913
914use refix_message::{GroupTable, InvalidValue, LazyKnownTags, Tag};
915
916/// An instance of the `NoPartySubIDs` (802) group.
917#[derive(Clone, Copy)]
918pub struct PtysSubGrp<'a>(refix_message::Scope<'a>);
919
920impl<'a> From<refix_message::Scope<'a>> for PtysSubGrp<'a> {
921    fn from(scope: refix_message::Scope<'a>) -> Self {
922        Self(scope)
923    }
924}
925
926impl<'a> PtysSubGrp<'a> {
927    pub(in super::super) const TABLE: GroupTable<'static> = GroupTable::new(
928        Tag(802),
929        Tag(523),
930        &[Tag(523)],
931        &[],
932    );
933
934    pub(in super::super) const fn known_tags() -> &'static LazyKnownTags {
935        static TAGS: LazyKnownTags = LazyKnownTags::new(&[Tag(523)], &[]);
936        &TAGS
937    }
938
939    pub fn raw(&self) -> refix_message::Scope<'a> {
940        self.0
941    }
942
943    /// The `PartySubID` (523) field.
944    #[doc(alias = "PartySubID")]
945    pub fn party_sub_id(&self) -> Result<Option<&'a str>, InvalidValue> {
946        self.0.get_str(Tag(523))
947    }
948}
949
950impl std::fmt::Debug for PtysSubGrp<'_> {
951    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
952        write!(f, "PtysSubGrp({})", self.0)
953    }
954}
955=== messages/mod.rs
956// @generated by refix codegen from toy.xml. Do not edit.
957#![cfg_attr(rustfmt, rustfmt::skip)]
958
959mod new_order_single;
960
961#[allow(unused_imports)]
962pub use self::{
963    new_order_single::NewOrderSingle,
964};
965=== messages/new_order_single.rs
966// @generated by refix codegen from toy.xml. Do not edit.
967#![cfg_attr(rustfmt, rustfmt::skip)]
968
969use refix_message::{Instances, InvalidValue, LazyKnownTags, RawMessage, Tag};
970
971use super::super::components::Parties;
972
973/// The `NewOrderSingle` (35=D) message.
974pub struct NewOrderSingle(RawMessage);
975
976impl NewOrderSingle {
977    pub const MSG_TYPE: &[u8] = b"D";
978
979    pub(in super::super) const fn known_tags() -> &'static LazyKnownTags {
980        static TAGS: LazyKnownTags = LazyKnownTags::new(&[Tag(453)], &[Parties::known_tags()]);
981        &TAGS
982    }
983
984    pub fn from_raw(raw: RawMessage) -> Self {
985        Self(raw)
986    }
987
988    pub fn raw(&self) -> &RawMessage {
989        &self.0
990    }
991
992    /// The instances of the `NoPartyIDs` (453) group.
993    #[doc(alias = "NoPartyIDs")]
994    pub fn party_ids(&self) -> Result<Instances<'_, Parties<'_>>, InvalidValue> {
995        self.0.get_group(&Parties::TABLE, &Self::known_tags().get()).map(Instances::from)
996    }
997}
998
999impl std::fmt::Debug for NewOrderSingle {
1000    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1001        write!(f, "NewOrderSingle({})", self.0)
1002    }
1003}
1004
1005impl std::fmt::Display for NewOrderSingle {
1006    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1007        std::fmt::Display::fmt(&self.0, f)
1008    }
1009}
1010"#;
1011
1012            let generated = package_of(spec);
1013            assert_eq!(listing(&generated), expected);
1014            assert!(generated.warnings.is_empty());
1015        }
1016
1017        #[test]
1018        fn a_shared_group_is_emitted_once() {
1019            let spec = parties_spec(vec![
1020                message("NewOrderSingle", "D", vec![component_ref("Parties")]),
1021                message("ExecutionReport", "8", vec![component_ref("Parties")]),
1022            ]);
1023
1024            let code = code_of(spec);
1025
1026            assert_eq!(code.matches("pub struct Parties<'a>").count(), 1);
1027            assert_eq!(code.matches("pub fn party_ids(&self)").count(), 2);
1028        }
1029
1030        #[test]
1031        fn a_message_group_type_shares_the_message_file() {
1032            let spec = spec_of(
1033                vec![message(
1034                    "Logon",
1035                    "A",
1036                    vec![group(384, vec![field_ref(372)])],
1037                )],
1038                vec![
1039                    field("NoMsgTypes", 384, DataType::NumInGroup),
1040                    field("RefMsgType", 372, DataType::String),
1041                ],
1042            );
1043
1044            let package = package_of(spec);
1045
1046            let code = file(&package, "messages/logon.rs");
1047            assert!(code.contains("pub struct Logon(RawMessage);"));
1048            assert!(code.contains("pub struct LogonMsgTypes<'a>"));
1049            assert!(
1050                code.contains("self.0.get_group(&LogonMsgTypes::TABLE, &Self::known_tags().get())")
1051            );
1052            assert!(
1053                file(&package, "messages/mod.rs").contains("    logon::{Logon, LogonMsgTypes},\n")
1054            );
1055        }
1056
1057        #[test]
1058        fn a_group_in_a_group_instance_gets_a_type_in_its_parents_file() {
1059            let mut spec = parties_spec(vec![message(
1060                "NewOrderSingle",
1061                "D",
1062                vec![component_ref("Parties")],
1063            )]);
1064            spec.components = vec![Component {
1065                name: "Parties".to_owned(),
1066                members: vec![group(
1067                    453,
1068                    vec![field_ref(448), group(802, vec![field_ref(523)])],
1069                )],
1070            }];
1071
1072            let generated = package_of(spec);
1073
1074            let code = file(&generated, "components/parties.rs");
1075            assert!(code.contains(
1076                "        &[Tag(448), Tag(802)],\n        &[PartiesPartySubIDs::TABLE],\n    );\n"
1077            ));
1078            assert!(code.contains(
1079                "    pub fn party_sub_ids(&self) -> Result<Instances<'a, PartiesPartySubIDs<'a>>, InvalidValue> {\n        self.0.get_group(&PartiesPartySubIDs::TABLE, &Self::known_tags().get()).map(Instances::from)\n    }\n"
1080            ));
1081            assert!(code.contains("pub struct Parties<'a>"));
1082            assert!(code.contains("pub struct PartiesPartySubIDs<'a>"));
1083            assert_eq!(generated.warnings, vec![]);
1084        }
1085    }
1086}