Skip to main content

refix_codegen/
rust.rs

1mod dialect;
2mod dispatch;
3mod docs;
4mod enums;
5mod error;
6mod groups;
7mod layout;
8mod messages;
9mod names;
10mod naming;
11mod views;
12
13use refix_dictionary::{Dictionary, dictionary};
14
15use crate::Generated;
16use crate::conversion::{Conversion, unclaimed_types, uses};
17use crate::envelope::Envelope;
18use dialect::emit_dialect;
19use dispatch::emit_dispatch;
20use enums::emit_enum;
21pub use error::Error;
22use groups::{emit_group_module, shared_groups};
23use messages::emit_message;
24use names::Names;
25use views::emit_view;
26
27pub fn generate(dictionary: &Dictionary, source: &str) -> Result<Generated, Error> {
28    let mut warnings = Vec::new();
29    let names = Names::new(dictionary, &mut warnings)?;
30    let envelope = Envelope::of(dictionary);
31
32    // The layout is the emitter's own, so rustfmt leaves it alone. That keeps
33    // the output byte-stable across rustfmt versions. A message may declare a
34    // group named like itself, a module in a module of the same name, which
35    // clippy flags in code its users cannot change.
36    let header = format!(
37        "// @generated by refix codegen from {source}. Do not edit.\n#![cfg_attr(rustfmt, rustfmt::skip)]\n#![allow(clippy::module_inception)]\n"
38    );
39    let enums: Vec<String> = dictionary
40        .fields()
41        .iter()
42        .filter(|field| Conversion::of(field).is_enum())
43        .map(|field| emit_enum(field, &names))
44        .collect();
45    let groups: Vec<String> = shared_groups(dictionary, &mut warnings)
46        .into_iter()
47        .map(|group| emit_group_module(group, &names))
48        .collect();
49    let views: Vec<String> = envelope
50        .sections
51        .iter()
52        .map(|section| emit_view(*section, dictionary, &envelope, &names))
53        .collect();
54    let messages: Vec<String> = dictionary
55        .messages()
56        .map(|message| emit_message(message, &envelope, &names))
57        .collect();
58    let sections = std::iter::once(emit_dialect(dictionary))
59        .chain(enums)
60        .chain(groups)
61        .chain(views)
62        .chain(messages)
63        .chain(emit_dispatch(dictionary))
64        .collect::<Vec<String>>()
65        .join("\n");
66    let has_groups = !envelope.with_groups.is_empty()
67        || dictionary.messages().any(|message| {
68            message
69                .members()
70                .any(|member| matches!(member, dictionary::Member::Group(_)))
71        });
72    let mut imports = vec!["Dialect", "InvalidValue", "KnownTags", "RawMessage", "Tag"];
73    if has_groups {
74        imports.extend(["GroupTable", "Instances"]);
75    }
76    if uses(dictionary, |conversion| {
77        matches!(
78            conversion,
79            Conversion::MultipleValues | Conversion::MultipleStr
80        )
81    }) {
82        imports.push("MultipleValues");
83    }
84    if uses(dictionary, |conversion| conversion == Conversion::Decimal) {
85        imports.push("Decimal");
86    }
87    if uses(dictionary, |conversion| conversion == Conversion::Date) {
88        imports.push("Date");
89    }
90    if uses(dictionary, |conversion| conversion == Conversion::MonthYear) {
91        imports.push("MonthYear");
92    }
93    if uses(dictionary, |conversion| conversion == Conversion::Time) {
94        imports.push("Time");
95    }
96    if uses(dictionary, |conversion| {
97        conversion == Conversion::UtcTimestamp
98    }) {
99        imports.push("UtcTimestamp");
100    }
101    imports.sort_unstable();
102    let imports = format!("use refix_message::{{{}}};", imports.join(", "));
103    let code = format!("{header}\n{imports}\n\n{sections}");
104
105    warnings.extend(unclaimed_types(dictionary));
106    Ok(Generated { code, warnings })
107}
108
109#[cfg(test)]
110mod tests {
111    use super::*;
112    use crate::Warning;
113    use refix_dictionary::spec::{
114        Category, DataType, EnumValue, Field, FieldRef, Group, Member, Message, Protocol, Spec,
115        Version,
116    };
117    use refix_dictionary::{MemberContext, Tag};
118
119    fn field(name: &str, tag: u32, data_type: DataType) -> Field {
120        Field {
121            name: name.to_owned(),
122            tag: Tag(tag),
123            data_type,
124            length_tag: None,
125            values: vec![],
126        }
127    }
128
129    fn spec_of(messages: Vec<Message>, fields: Vec<Field>) -> Spec {
130        Spec {
131            version: Version {
132                protocol: Protocol::Fix,
133                major: 4,
134                minor: 4,
135                service_pack: 0,
136            },
137            header: vec![],
138            trailer: vec![],
139            messages,
140            components: vec![],
141            fields,
142        }
143    }
144
145    #[test]
146    fn generates_a_complete_module() {
147        let mut ord_type = field("OrdType", 40, DataType::Char);
148        ord_type.values = vec![
149            EnumValue {
150                value: "1".to_owned(),
151                description: "MARKET".to_owned(),
152            },
153            EnumValue {
154                value: "2".to_owned(),
155                description: "LIMIT".to_owned(),
156            },
157        ];
158        let spec = spec_of(
159            vec![Message {
160                name: "NewOrderSingle".to_owned(),
161                msg_type: "D".to_owned(),
162                members: vec![
163                    Member::Field(FieldRef {
164                        tag: Tag(11),
165                        is_required: true,
166                    }),
167                    Member::Field(FieldRef {
168                        tag: Tag(38),
169                        is_required: false,
170                    }),
171                    Member::Field(FieldRef {
172                        tag: Tag(44),
173                        is_required: false,
174                    }),
175                    Member::Field(FieldRef {
176                        tag: Tag(40),
177                        is_required: false,
178                    }),
179                ],
180                category: Category::App,
181            }],
182            vec![
183                field("ClOrdID", 11, DataType::String),
184                field("OrderQty", 38, DataType::Int),
185                field("Price", 44, DataType::Other("PRICE".to_owned())),
186                ord_type,
187            ],
188        );
189
190        let expected = r#"// @generated by refix codegen from toy.xml. Do not edit.
191#![cfg_attr(rustfmt, rustfmt::skip)]
192#![allow(clippy::module_inception)]
193
194use refix_message::{Dialect, InvalidValue, KnownTags, RawMessage, Tag};
195
196/// The dialect of this dictionary.
197pub const DIALECT: Dialect<'static> = Dialect::new();
198
199/// The values of the `OrdType` (40) field.
200#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
201pub enum OrdType<'a> {
202    /// `1`
203    Market,
204    /// `2`
205    Limit,
206    /// A value the dictionary does not list.
207    Unrecognized(&'a str),
208}
209
210impl<'a> OrdType<'a> {
211    pub fn from_value(value: &'a str) -> Self {
212        match value {
213            "1" => Self::Market,
214            "2" => Self::Limit,
215            unrecognized => Self::Unrecognized(unrecognized),
216        }
217    }
218
219    pub fn value(self) -> &'a str {
220        match self {
221            Self::Market => "1",
222            Self::Limit => "2",
223            Self::Unrecognized(value) => value,
224        }
225    }
226}
227
228impl<'a> From<&'a str> for OrdType<'a> {
229    fn from(value: &'a str) -> Self {
230        Self::from_value(value)
231    }
232}
233
234/// The `NewOrderSingle` (35=D) message.
235pub struct NewOrderSingle(RawMessage);
236
237impl NewOrderSingle {
238    pub const MSG_TYPE: &[u8] = b"D";
239
240    pub const KNOWN_TAGS: KnownTags<'static> = KnownTags::new(&[
241        Tag(11), Tag(38), Tag(40), Tag(44),
242    ]);
243
244    pub fn from_raw(raw: RawMessage) -> Self {
245        Self(raw)
246    }
247
248    pub fn raw(&self) -> &RawMessage {
249        &self.0
250    }
251
252    /// The `ClOrdID` (11) field.
253    #[doc(alias = "ClOrdID")]
254    pub fn cl_ord_id(&self) -> Result<Option<&str>, InvalidValue> {
255        self.0.get_str(Tag(11))
256    }
257
258    /// The `OrderQty` (38) field.
259    #[doc(alias = "OrderQty")]
260    pub fn order_qty(&self) -> Result<Option<i64>, InvalidValue> {
261        self.0.get_int(Tag(38))
262    }
263
264    /// The `Price` (44) field.
265    #[doc(alias = "Price")]
266    pub fn price_raw(&self) -> Option<&[u8]> {
267        self.0.get(Tag(44))
268    }
269
270    /// The `OrdType` (40) field.
271    #[doc(alias = "OrdType")]
272    pub fn ord_type(&self) -> Result<Option<OrdType<'_>>, InvalidValue> {
273        Ok(self.0.get_str(Tag(40))?.map(OrdType::from_value))
274    }
275}
276
277impl std::fmt::Debug for NewOrderSingle {
278    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
279        write!(f, "NewOrderSingle({})", self.0)
280    }
281}
282
283impl std::fmt::Display for NewOrderSingle {
284    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
285        std::fmt::Display::fmt(&self.0, f)
286    }
287}
288
289/// A message read as the type its MsgType names.
290pub enum Message {
291    NewOrderSingle(NewOrderSingle),
292    Unrecognized(RawMessage),
293}
294
295impl Message {
296    pub fn from_raw(raw: RawMessage) -> Self {
297        match raw.get(Tag(35)) {
298            Some(NewOrderSingle::MSG_TYPE) => Self::NewOrderSingle(NewOrderSingle::from_raw(raw)),
299            _ => Self::Unrecognized(raw),
300        }
301    }
302}
303
304impl std::fmt::Debug for Message {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        match self {
307            Self::NewOrderSingle(message) => std::fmt::Debug::fmt(message, f),
308            Self::Unrecognized(raw) => write!(f, "Unrecognized({raw})"),
309        }
310    }
311}
312
313impl std::fmt::Display for Message {
314    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
315        match self {
316            Self::NewOrderSingle(message) => std::fmt::Display::fmt(message, f),
317            Self::Unrecognized(raw) => std::fmt::Display::fmt(raw, f),
318        }
319    }
320}
321"#;
322
323        let generated = generate(&spec.resolve().unwrap().dictionary, "toy.xml").unwrap();
324        assert_eq!(generated.code, expected);
325        assert_eq!(
326            generated.warnings,
327            [Warning::UnclaimedType {
328                field: "Price".to_owned(),
329                data_type: DataType::Other("PRICE".to_owned()),
330            }]
331        );
332    }
333
334    #[test]
335    fn a_dictionary_without_messages_has_no_message_enum() {
336        let spec = spec_of(vec![], vec![]);
337
338        let code = generate(&spec.resolve().unwrap().dictionary, "toy.xml")
339            .unwrap()
340            .code;
341
342        assert!(!code.contains("pub enum Message"));
343    }
344
345    #[test]
346    fn the_dialect_lists_every_linked_length_tag_in_order() {
347        let spec = spec_of(
348            vec![],
349            vec![
350                field("VenueDataLen", 5001, DataType::Length),
351                Field {
352                    length_tag: Some(Tag(5001)),
353                    ..field("VenueData", 5002, DataType::Data)
354                },
355                field("RawDataLength", 95, DataType::Length),
356                Field {
357                    length_tag: Some(Tag(95)),
358                    ..field("RawData", 96, DataType::Data)
359                },
360            ],
361        );
362
363        let code = generate(&spec.resolve().unwrap().dictionary, "toy.xml")
364            .unwrap()
365            .code;
366
367        assert!(code.contains(
368            "pub const DIALECT: Dialect<'static> = Dialect::new().with_extra_length_tags(&[Tag(95), Tag(5001)]);\n"
369        ));
370    }
371
372    #[test]
373    fn imports_multiple_values_only_when_read() {
374        let mut exec_inst = field("ExecInst", 18, DataType::MultipleStringValue);
375        exec_inst.values = vec![EnumValue {
376            value: "1".to_owned(),
377            description: "NOT_HELD".to_owned(),
378        }];
379        let order = |members| Message {
380            name: "NewOrderSingle".to_owned(),
381            msg_type: "D".to_owned(),
382            members,
383            category: Category::App,
384        };
385        let reads = spec_of(
386            vec![order(vec![Member::Field(FieldRef {
387                tag: Tag(18),
388                is_required: false,
389            })])],
390            vec![exec_inst.clone()],
391        );
392        let unused = spec_of(vec![order(vec![])], vec![exec_inst]);
393
394        let imports = |spec: Spec| {
395            let code = generate(&spec.resolve().unwrap().dictionary, "toy.xml")
396                .unwrap()
397                .code;
398            code.lines()
399                .find(|line| line.starts_with("use "))
400                .unwrap()
401                .to_owned()
402        };
403
404        assert_eq!(
405            imports(reads),
406            "use refix_message::{Dialect, InvalidValue, KnownTags, MultipleValues, RawMessage, Tag};"
407        );
408        assert_eq!(
409            imports(unused),
410            "use refix_message::{Dialect, InvalidValue, KnownTags, RawMessage, Tag};"
411        );
412    }
413
414    #[test]
415    fn imports_value_types_only_when_read() {
416        let order = |members| Message {
417            name: "NewOrderSingle".to_owned(),
418            msg_type: "D".to_owned(),
419            members,
420            category: Category::App,
421        };
422        let imports = |spec: Spec| {
423            let code = generate(&spec.resolve().unwrap().dictionary, "toy.xml")
424                .unwrap()
425                .code;
426            code.lines()
427                .find(|line| line.starts_with("use "))
428                .unwrap()
429                .to_owned()
430        };
431
432        for (value, expected) in [
433            (
434                field("Price", 44, DataType::Price),
435                "use refix_message::{Decimal, Dialect, InvalidValue, KnownTags, RawMessage, Tag};",
436            ),
437            (
438                field("SettlDate", 64, DataType::LocalMktDate),
439                "use refix_message::{Date, Dialect, InvalidValue, KnownTags, RawMessage, Tag};",
440            ),
441            (
442                field("MaturityMonthYear", 200, DataType::MonthYear),
443                "use refix_message::{Dialect, InvalidValue, KnownTags, MonthYear, RawMessage, Tag};",
444            ),
445            (
446                field("MDEntryTime", 273, DataType::UtcTimeOnly),
447                "use refix_message::{Dialect, InvalidValue, KnownTags, RawMessage, Tag, Time};",
448            ),
449            (
450                field("TransactTime", 60, DataType::UtcTimestamp),
451                "use refix_message::{Dialect, InvalidValue, KnownTags, RawMessage, Tag, UtcTimestamp};",
452            ),
453            (
454                field("DeskOrderHandlingInst", 1035, DataType::MultipleStringValue),
455                "use refix_message::{Dialect, InvalidValue, KnownTags, MultipleValues, RawMessage, Tag};",
456            ),
457        ] {
458            let reads = spec_of(
459                vec![order(vec![Member::Field(FieldRef {
460                    tag: value.tag,
461                    is_required: false,
462                })])],
463                vec![value.clone()],
464            );
465            let unused = spec_of(vec![order(vec![])], vec![value]);
466
467            assert_eq!(imports(reads), expected);
468            assert_eq!(
469                imports(unused),
470                "use refix_message::{Dialect, InvalidValue, KnownTags, RawMessage, Tag};"
471            );
472        }
473    }
474
475    #[test]
476    fn a_boolean_reads_as_a_bool_without_an_enum() {
477        let mut locate_reqd = field("LocateReqd", 114, DataType::Boolean);
478        locate_reqd.values = [("Y", "YES"), ("N", "NO")]
479            .map(|(value, description)| EnumValue {
480                value: value.to_owned(),
481                description: description.to_owned(),
482            })
483            .to_vec();
484        let spec = spec_of(
485            vec![Message {
486                name: "NewOrderSingle".to_owned(),
487                msg_type: "D".to_owned(),
488                members: vec![Member::Field(FieldRef {
489                    tag: Tag(114),
490                    is_required: false,
491                })],
492                category: Category::App,
493            }],
494            vec![locate_reqd],
495        );
496
497        let code = generate(&spec.resolve().unwrap().dictionary, "toy.xml")
498            .unwrap()
499            .code;
500
501        assert!(code.contains("pub fn locate_reqd(&self) -> Result<Option<bool>, InvalidValue> {"));
502        assert!(!code.contains("enum LocateReqd"));
503    }
504
505    #[test]
506    fn an_enum_named_like_a_message_is_renamed_with_a_warning() {
507        let mut security_status = field("SecurityStatus", 965, DataType::String);
508        security_status.values = vec![EnumValue {
509            value: "1".to_owned(),
510            description: "ACTIVE".to_owned(),
511        }];
512        let spec = spec_of(
513            vec![Message {
514                name: "SecurityStatus".to_owned(),
515                msg_type: "f".to_owned(),
516                members: vec![Member::Field(FieldRef {
517                    tag: Tag(965),
518                    is_required: false,
519                })],
520                category: Category::App,
521            }],
522            vec![security_status],
523        );
524
525        let generated = generate(&spec.resolve().unwrap().dictionary, "toy.xml").unwrap();
526
527        assert!(generated.code.contains("pub enum SecurityStatusEnum<'a> {"));
528        assert!(
529            generated
530                .code
531                .contains("pub struct SecurityStatus(RawMessage);")
532        );
533        assert!(
534            generated
535                .code
536                .contains("Result<Option<SecurityStatusEnum<'_>>, InvalidValue>")
537        );
538        assert!(matches!(
539            generated.warnings.as_slice(),
540            [Warning::Renamed { .. }]
541        ));
542    }
543
544    #[test]
545    fn emits_messages_in_spec_order() {
546        let spec = spec_of(
547            vec![
548                Message {
549                    name: "Heartbeat".to_owned(),
550                    msg_type: "0".to_owned(),
551                    members: vec![],
552                    category: Category::Admin,
553                },
554                Message {
555                    name: "TestRequest".to_owned(),
556                    msg_type: "1".to_owned(),
557                    members: vec![],
558                    category: Category::Admin,
559                },
560            ],
561            vec![],
562        );
563
564        let generated = generate(&spec.resolve().unwrap().dictionary, "toy.xml").unwrap();
565
566        let heartbeat = generated.code.find("pub struct Heartbeat").unwrap();
567        let test_request = generated.code.find("pub struct TestRequest").unwrap();
568        assert!(heartbeat < test_request);
569    }
570
571    mod groups {
572        use super::*;
573        use refix_dictionary::spec::{Component, ComponentRef};
574
575        fn field_ref(tag: u32) -> Member {
576            Member::Field(FieldRef {
577                tag: Tag(tag),
578                is_required: false,
579            })
580        }
581
582        fn component_ref(name: &str) -> Member {
583            Member::Component(ComponentRef {
584                name: name.to_owned(),
585                is_required: false,
586            })
587        }
588
589        fn group(count_tag: u32, members: Vec<Member>) -> Member {
590            Member::Group(Group {
591                count_tag: Tag(count_tag),
592                is_required: false,
593                members,
594            })
595        }
596
597        fn message(name: &str, msg_type: &str, members: Vec<Member>) -> Message {
598            Message {
599                name: name.to_owned(),
600                msg_type: msg_type.to_owned(),
601                members,
602                category: Category::App,
603            }
604        }
605
606        /// A spec with `Parties` and its nested `PtysSubGrp`, as FIX44
607        /// declares them, used by `messages`.
608        fn parties_spec(messages: Vec<Message>) -> Spec {
609            let mut spec = spec_of(
610                messages,
611                vec![
612                    field("NoPartyIDs", 453, DataType::NumInGroup),
613                    field("PartyID", 448, DataType::String),
614                    field("NoPartySubIDs", 802, DataType::NumInGroup),
615                    field("PartySubID", 523, DataType::String),
616                ],
617            );
618            spec.components = vec![
619                Component {
620                    name: "Parties".to_owned(),
621                    members: vec![group(
622                        453,
623                        vec![field_ref(448), component_ref("PtysSubGrp")],
624                    )],
625                },
626                Component {
627                    name: "PtysSubGrp".to_owned(),
628                    members: vec![group(802, vec![field_ref(523)])],
629                },
630            ];
631            spec
632        }
633
634        fn generated(spec: Spec) -> Generated {
635            generate(&spec.resolve().unwrap().dictionary, "toy.xml").unwrap()
636        }
637
638        #[test]
639        fn generates_a_module_per_group() {
640            let spec = parties_spec(vec![message(
641                "NewOrderSingle",
642                "D",
643                vec![component_ref("Parties")],
644            )]);
645
646            let expected = r#"// @generated by refix codegen from toy.xml. Do not edit.
647#![cfg_attr(rustfmt, rustfmt::skip)]
648#![allow(clippy::module_inception)]
649
650use refix_message::{Dialect, GroupTable, Instances, InvalidValue, KnownTags, RawMessage, Tag};
651
652/// The dialect of this dictionary.
653pub const DIALECT: Dialect<'static> = Dialect::new();
654
655pub mod parties {
656    use super::*;
657
658    pub const TABLE: GroupTable<'static> = GroupTable::new(
659        Tag(453),
660        Tag(448),
661        &[Tag(448), Tag(802)],
662        &[ptys_sub_grp::TABLE],
663    );
664
665    pub const KNOWN_TAGS: KnownTags<'static> = KnownTags::new(&[Tag(448), Tag(523), Tag(802)]);
666
667    #[derive(Clone, Copy, Debug)]
668    pub struct Instance<'a>(refix_message::Scope<'a>);
669
670    impl<'a> From<refix_message::Scope<'a>> for Instance<'a> {
671        fn from(scope: refix_message::Scope<'a>) -> Self {
672            Self(scope)
673        }
674    }
675
676    impl<'a> Instance<'a> {
677        pub fn raw(&self) -> refix_message::Scope<'a> {
678            self.0
679        }
680
681        /// The `PartyID` (448) field.
682        #[doc(alias = "PartyID")]
683        pub fn party_id(&self) -> Result<Option<&'a str>, InvalidValue> {
684            self.0.get_str(Tag(448))
685        }
686
687        /// The instances of the `NoPartySubIDs` (802) group.
688        #[doc(alias = "NoPartySubIDs")]
689        pub fn party_sub_ids(&self) -> Result<Instances<'a, ptys_sub_grp::Instance<'a>>, InvalidValue> {
690            self.0.get_group(&ptys_sub_grp::TABLE, &KNOWN_TAGS).map(Instances::from)
691        }
692    }
693}
694
695pub mod ptys_sub_grp {
696    use super::*;
697
698    pub const TABLE: GroupTable<'static> = GroupTable::new(Tag(802), Tag(523), &[Tag(523)], &[]);
699
700    pub const KNOWN_TAGS: KnownTags<'static> = KnownTags::new(&[Tag(523)]);
701
702    #[derive(Clone, Copy, Debug)]
703    pub struct Instance<'a>(refix_message::Scope<'a>);
704
705    impl<'a> From<refix_message::Scope<'a>> for Instance<'a> {
706        fn from(scope: refix_message::Scope<'a>) -> Self {
707            Self(scope)
708        }
709    }
710
711    impl<'a> Instance<'a> {
712        pub fn raw(&self) -> refix_message::Scope<'a> {
713            self.0
714        }
715
716        /// The `PartySubID` (523) field.
717        #[doc(alias = "PartySubID")]
718        pub fn party_sub_id(&self) -> Result<Option<&'a str>, InvalidValue> {
719            self.0.get_str(Tag(523))
720        }
721    }
722}
723
724/// The `NewOrderSingle` (35=D) message.
725pub struct NewOrderSingle(RawMessage);
726
727impl NewOrderSingle {
728    pub const MSG_TYPE: &[u8] = b"D";
729
730    pub const KNOWN_TAGS: KnownTags<'static> = KnownTags::new(&[
731        Tag(448), Tag(453), Tag(523), Tag(802),
732    ]);
733
734    pub fn from_raw(raw: RawMessage) -> Self {
735        Self(raw)
736    }
737
738    pub fn raw(&self) -> &RawMessage {
739        &self.0
740    }
741
742    /// The instances of the `NoPartyIDs` (453) group.
743    #[doc(alias = "NoPartyIDs")]
744    pub fn party_ids(&self) -> Result<Instances<'_, parties::Instance<'_>>, InvalidValue> {
745        self.0.get_group(&parties::TABLE, &Self::KNOWN_TAGS).map(Instances::from)
746    }
747}
748
749impl std::fmt::Debug for NewOrderSingle {
750    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
751        write!(f, "NewOrderSingle({})", self.0)
752    }
753}
754
755impl std::fmt::Display for NewOrderSingle {
756    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
757        std::fmt::Display::fmt(&self.0, f)
758    }
759}
760
761/// A message read as the type its MsgType names.
762pub enum Message {
763    NewOrderSingle(NewOrderSingle),
764    Unrecognized(RawMessage),
765}
766
767impl Message {
768    pub fn from_raw(raw: RawMessage) -> Self {
769        match raw.get(Tag(35)) {
770            Some(NewOrderSingle::MSG_TYPE) => Self::NewOrderSingle(NewOrderSingle::from_raw(raw)),
771            _ => Self::Unrecognized(raw),
772        }
773    }
774}
775
776impl std::fmt::Debug for Message {
777    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
778        match self {
779            Self::NewOrderSingle(message) => std::fmt::Debug::fmt(message, f),
780            Self::Unrecognized(raw) => write!(f, "Unrecognized({raw})"),
781        }
782    }
783}
784
785impl std::fmt::Display for Message {
786    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
787        match self {
788            Self::NewOrderSingle(message) => std::fmt::Display::fmt(message, f),
789            Self::Unrecognized(raw) => std::fmt::Display::fmt(raw, f),
790        }
791    }
792}
793"#;
794
795            let generated = generated(spec);
796            assert_eq!(generated.code, expected);
797            assert!(generated.warnings.is_empty());
798        }
799
800        #[test]
801        fn a_shared_group_is_emitted_once() {
802            let spec = parties_spec(vec![
803                message("NewOrderSingle", "D", vec![component_ref("Parties")]),
804                message("ExecutionReport", "8", vec![component_ref("Parties")]),
805            ]);
806
807            let code = generated(spec).code;
808
809            assert_eq!(code.matches("pub mod parties {").count(), 1);
810            assert_eq!(code.matches("pub fn party_ids(&self)").count(), 2);
811        }
812
813        #[test]
814        fn group_modules_come_in_order_of_first_appearance() {
815            let spec = parties_spec(vec![
816                message("PartyDetails", "CG", vec![component_ref("PtysSubGrp")]),
817                message("NewOrderSingle", "D", vec![component_ref("Parties")]),
818            ]);
819
820            let code = generated(spec).code;
821
822            let ptys_sub_grp = code.find("pub mod ptys_sub_grp {").unwrap();
823            let parties = code.find("pub mod parties {").unwrap();
824            assert!(ptys_sub_grp < parties);
825        }
826
827        #[test]
828        fn a_message_group_nests_under_the_message_module() {
829            let spec = spec_of(
830                vec![message(
831                    "Logon",
832                    "A",
833                    vec![group(384, vec![field_ref(372)])],
834                )],
835                vec![
836                    field("NoMsgTypes", 384, DataType::NumInGroup),
837                    field("RefMsgType", 372, DataType::String),
838                ],
839            );
840
841            let code = generated(spec).code;
842
843            assert!(code.contains(
844                "pub mod logon {\n    pub mod msg_types {\n        use super::super::*;\n"
845            ));
846            assert!(code.contains("self.0.get_group(&logon::msg_types::TABLE, &Self::KNOWN_TAGS)"));
847        }
848
849        #[test]
850        fn a_group_in_a_group_instance_is_skipped_with_a_warning() {
851            let mut spec = parties_spec(vec![message(
852                "NewOrderSingle",
853                "D",
854                vec![component_ref("Parties")],
855            )]);
856            spec.components = vec![Component {
857                name: "Parties".to_owned(),
858                members: vec![group(
859                    453,
860                    vec![field_ref(448), group(802, vec![field_ref(523)])],
861                )],
862            }];
863
864            let generated = generated(spec);
865
866            assert!(!generated.code.contains("party_sub_ids"));
867            assert!(
868                generated
869                    .code
870                    .contains("&[GroupTable::new(Tag(802), Tag(523), &[Tag(523)], &[])]")
871            );
872            assert_eq!(
873                generated.warnings,
874                vec![Warning::UnsupportedGroup {
875                    context: MemberContext::Component("Parties".to_owned())
876                        .group("NoPartyIDs")
877                        .group("NoPartySubIDs"),
878                }]
879            );
880        }
881    }
882}