Skip to main content

refix_dictionary/
dictionary.rs

1//! The validated, resolved form of a data dictionary.
2//!
3//! A [`Dictionary`] can only be obtained by resolving a [`Spec`], so
4//! holding one proves its references are valid, and reads are infallible.
5
6mod error;
7mod resolver;
8
9use crate::{Category, Field, MemberContext, Spec, Version, spec};
10pub use error::Error;
11use std::fmt;
12use std::ops::Index;
13
14/// A resolved data dictionary, produced by [`Spec::resolve`].
15#[derive(Clone, Debug)]
16pub struct Dictionary {
17    spec: Spec,
18    header: Vec<ResolvedMember>,
19    messages: Vec<ResolvedMessage>,
20    trailer: Vec<ResolvedMember>,
21}
22
23#[derive(Clone, Debug)]
24struct ResolvedMessage {
25    members: Vec<ResolvedMember>,
26}
27
28/// A member as indices into the spec's field definitions, so the
29/// dictionary stays free of self-references.
30#[derive(Clone, Debug, Eq, PartialEq)]
31enum ResolvedMember {
32    Field {
33        field_index: FieldIndex,
34        is_required: bool,
35    },
36    Group(ResolvedGroup),
37}
38
39#[derive(Clone, Debug, Eq, PartialEq)]
40struct ResolvedGroup {
41    count_field_index: FieldIndex,
42    delimiter_index: FieldIndex,
43    is_required: bool,
44    declared_in: MemberContext,
45    /// The component this group makes up, when it is that component's only
46    /// member.
47    component: Option<String>,
48    members: Vec<ResolvedMember>,
49}
50
51/// A position in the spec's field definitions.
52#[derive(Clone, Copy, Debug, Eq, PartialEq)]
53struct FieldIndex(usize);
54
55/// A position in the spec's component definitions.
56#[derive(Clone, Copy, Debug, Eq, PartialEq)]
57struct ComponentIndex(usize);
58
59impl Index<FieldIndex> for [Field] {
60    type Output = Field;
61
62    fn index(&self, index: FieldIndex) -> &Field {
63        &self[index.0]
64    }
65}
66
67impl Index<ComponentIndex> for [spec::Component] {
68    type Output = spec::Component;
69
70    fn index(&self, index: ComponentIndex) -> &spec::Component {
71        &self[index.0]
72    }
73}
74
75impl Dictionary {
76    pub fn version(&self) -> Version {
77        self.spec.version
78    }
79
80    /// The field definitions, as declared in the spec.
81    pub fn fields(&self) -> &[Field] {
82        &self.spec.fields
83    }
84
85    /// The members every message starts with, in source order, components
86    /// expanded in place.
87    pub fn header(&self) -> impl Iterator<Item = Member<'_>> {
88        members_of(&self.header, &self.spec.fields)
89    }
90
91    /// The messages, with references resolved and components expanded.
92    pub fn messages(&self) -> impl Iterator<Item = Message<'_>> {
93        self.spec
94            .messages
95            .iter()
96            .zip(&self.messages)
97            .map(|(declared, resolved)| Message {
98                declared,
99                members: &resolved.members,
100                fields: &self.spec.fields,
101            })
102    }
103
104    /// The members every message ends with, in source order, components
105    /// expanded in place.
106    pub fn trailer(&self) -> impl Iterator<Item = Member<'_>> {
107        members_of(&self.trailer, &self.spec.fields)
108    }
109
110    /// The spec this dictionary was resolved from, for structural queries.
111    pub fn spec(&self) -> &Spec {
112        &self.spec
113    }
114}
115
116/// A read view of one message, with its member list resolved.
117#[derive(Clone, Copy)]
118pub struct Message<'a> {
119    declared: &'a spec::Message,
120    members: &'a [ResolvedMember],
121    fields: &'a [Field],
122}
123
124impl<'a> Message<'a> {
125    pub fn name(&self) -> &'a str {
126        &self.declared.name
127    }
128
129    /// The wire value of `MsgType(35)`, verbatim, e.g. `"D"`.
130    pub fn msg_type(&self) -> &'a str {
131        &self.declared.msg_type
132    }
133
134    pub fn category(&self) -> Category {
135        self.declared.category
136    }
137
138    /// The members in source order, components expanded in place.
139    pub fn members(&self) -> impl Iterator<Item = Member<'a>> {
140        members_of(self.members, self.fields)
141    }
142}
143
144/// A member of a message or group instance, with its references resolved.
145#[derive(Clone, Copy, Debug, Eq, PartialEq)]
146pub enum Member<'a> {
147    Field {
148        /// The referenced field definition.
149        field: &'a Field,
150        /// Whether the field is required at every level on the path to it.
151        is_required: bool,
152    },
153    Group(Group<'a>),
154}
155
156/// A read view of one repeating group, with its instance members resolved.
157#[derive(Clone, Copy, Eq, PartialEq)]
158pub struct Group<'a> {
159    resolved: &'a ResolvedGroup,
160    fields: &'a [Field],
161}
162
163impl<'a> Group<'a> {
164    /// The NumInGroup field, e.g. `NoPartyIDs(453)`.
165    pub fn count_field(&self) -> &'a Field {
166        &self.fields[self.resolved.count_field_index]
167    }
168
169    /// The field every instance starts with.
170    ///
171    /// That is the instance's first field after expansion, or a nested
172    /// group's count field.
173    pub fn delimiter(&self) -> &'a Field {
174        &self.fields[self.resolved.delimiter_index]
175    }
176
177    /// Whether the count field is required in the enclosing scope,
178    /// combined across every component on the path to it.
179    pub fn is_required(&self) -> bool {
180        self.resolved.is_required
181    }
182
183    /// The message, component, group instance, header or trailer the
184    /// `<group>` element sits in.
185    pub fn declared_in(&self) -> &'a MemberContext {
186        &self.resolved.declared_in
187    }
188
189    /// The component this group makes up, when it is that component's only
190    /// member.
191    pub fn component(&self) -> Option<&'a str> {
192        self.resolved.component.as_deref()
193    }
194
195    /// The members of each instance in source order, with requiredness
196    /// relative to the instance.
197    pub fn members(&self) -> impl Iterator<Item = Member<'a>> {
198        members_of(&self.resolved.members, self.fields)
199    }
200}
201
202impl fmt::Debug for Group<'_> {
203    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204        f.debug_struct("Group")
205            .field("count_field", &self.count_field().name)
206            .field("is_required", &self.is_required())
207            .field("members", &self.members().collect::<Vec<_>>())
208            .finish()
209    }
210}
211
212fn members_of<'a>(
213    members: &'a [ResolvedMember],
214    fields: &'a [Field],
215) -> impl Iterator<Item = Member<'a>> {
216    members.iter().map(move |member| match member {
217        ResolvedMember::Field {
218            field_index,
219            is_required,
220        } => Member::Field {
221            field: &fields[*field_index],
222            is_required: *is_required,
223        },
224        ResolvedMember::Group(group) => Member::Group(Group {
225            resolved: group,
226            fields,
227        }),
228    })
229}
230
231#[cfg(test)]
232mod tests {
233    use super::*;
234    use crate::{Component, ComponentRef, DataType, FieldRef, MemberContext, Protocol, Tag};
235
236    fn field(name: &str, tag: u32) -> Field {
237        Field {
238            name: name.to_owned(),
239            tag: Tag(tag),
240            data_type: DataType::String,
241            values: vec![],
242        }
243    }
244
245    fn field_ref(tag: u32, is_required: bool) -> spec::Member {
246        spec::Member::Field(FieldRef {
247            tag: Tag(tag),
248            is_required,
249        })
250    }
251
252    /// Members as (tag, is_required), for member lists without groups.
253    fn field_members<'a>(members: impl Iterator<Item = Member<'a>>) -> Vec<(Tag, bool)> {
254        members
255            .map(|member| match member {
256                Member::Field { field, is_required } => (field.tag, is_required),
257                Member::Group(group) => panic!("unexpected group {}", group.count_field().name),
258            })
259            .collect()
260    }
261
262    fn component_ref(name: &str, is_required: bool) -> spec::Member {
263        spec::Member::Component(ComponentRef {
264            name: name.to_owned(),
265            is_required,
266        })
267    }
268
269    fn component(name: &str, members: Vec<spec::Member>) -> Component {
270        Component {
271            name: name.to_owned(),
272            members,
273        }
274    }
275
276    fn message(name: &str, members: Vec<spec::Member>) -> spec::Message {
277        spec::Message {
278            name: name.to_owned(),
279            msg_type: "D".to_owned(),
280            members,
281            category: Category::App,
282        }
283    }
284
285    fn spec_of(
286        fields: Vec<Field>,
287        components: Vec<Component>,
288        messages: Vec<spec::Message>,
289    ) -> Spec {
290        Spec {
291            version: Version {
292                protocol: Protocol::Fix,
293                major: 4,
294                minor: 4,
295                service_pack: 0,
296            },
297            header: vec![],
298            trailer: vec![],
299            messages,
300            fields,
301            components,
302        }
303    }
304
305    #[test]
306    fn resolves_direct_field_references() {
307        let spec = spec_of(
308            vec![field("ClOrdID", 11), field("Text", 58)],
309            vec![],
310            vec![message(
311                "NewOrderSingle",
312                vec![field_ref(11, true), field_ref(58, false)],
313            )],
314        );
315
316        let dictionary = spec.resolve().unwrap();
317
318        let messages: Vec<Message> = dictionary.messages().collect();
319        assert_eq!(messages.len(), 1);
320        assert_eq!(messages[0].name(), "NewOrderSingle");
321        assert_eq!(messages[0].msg_type(), "D");
322        assert_eq!(messages[0].category(), Category::App);
323        assert_eq!(
324            messages[0].members().collect::<Vec<Member>>(),
325            vec![
326                Member::Field {
327                    field: &dictionary.fields()[0],
328                    is_required: true,
329                },
330                Member::Field {
331                    field: &dictionary.fields()[1],
332                    is_required: false,
333                },
334            ]
335        );
336    }
337
338    #[test]
339    fn resolves_the_header_and_trailer() {
340        let mut spec = spec_of(
341            vec![
342                field("SenderCompID", 49),
343                field("TargetCompID", 56),
344                field("CheckSum", 10),
345            ],
346            vec![component("Target", vec![field_ref(56, true)])],
347            vec![],
348        );
349        spec.header = vec![field_ref(49, true), component_ref("Target", false)];
350        spec.trailer = vec![field_ref(10, true)];
351
352        let dictionary = spec.resolve().unwrap();
353
354        assert_eq!(
355            field_members(dictionary.header()),
356            [(Tag(49), true), (Tag(56), false)]
357        );
358        assert_eq!(field_members(dictionary.trailer()), [(Tag(10), true)]);
359    }
360
361    #[test]
362    fn a_header_group_is_declared_in_the_header() {
363        let mut spec = spec_of(
364            vec![field("NoHops", 627), field("HopCompID", 628)],
365            vec![],
366            vec![],
367        );
368        spec.header = vec![spec::Member::Group(spec::Group {
369            count_tag: Tag(627),
370            is_required: false,
371            members: vec![field_ref(628, false)],
372        })];
373
374        let dictionary = spec.resolve().unwrap();
375
376        let Some(Member::Group(hops)) = dictionary.header().next() else {
377            panic!("expected the hops group");
378        };
379        assert_eq!(hops.declared_in(), &MemberContext::Header);
380    }
381
382    #[test]
383    fn a_header_tag_in_a_message_is_an_error() {
384        let mut spec = spec_of(
385            vec![field("ClOrdID", 11), field("SenderCompID", 49)],
386            vec![],
387            vec![message(
388                "NewOrderSingle",
389                vec![field_ref(11, true), field_ref(49, false)],
390            )],
391        );
392        spec.header = vec![field_ref(49, true)];
393
394        let error = spec.resolve().unwrap_err();
395
396        assert_eq!(
397            error,
398            Error::DuplicateField {
399                tag: Tag(49),
400                first: MemberContext::Header,
401                second: MemberContext::Message("NewOrderSingle".to_owned()),
402            }
403        );
404        assert_eq!(
405            error.to_string(),
406            "tag 49 appears in both the header and message 'NewOrderSingle'"
407        );
408    }
409
410    #[test]
411    fn a_trailer_tag_in_a_message_is_an_error() {
412        let mut spec = spec_of(
413            vec![field("Signature", 89)],
414            vec![],
415            vec![message("NewOrderSingle", vec![field_ref(89, false)])],
416        );
417        spec.trailer = vec![field_ref(89, false)];
418
419        assert_eq!(
420            spec.resolve().unwrap_err(),
421            Error::DuplicateField {
422                tag: Tag(89),
423                first: MemberContext::Message("NewOrderSingle".to_owned()),
424                second: MemberContext::Trailer,
425            }
426        );
427    }
428
429    #[test]
430    fn an_unknown_trailer_field_names_the_trailer() {
431        let mut spec = spec_of(vec![], vec![], vec![]);
432        spec.trailer = vec![field_ref(10, true)];
433
434        assert_eq!(
435            spec.resolve().unwrap_err(),
436            Error::UnknownField {
437                tag: Tag(10),
438                context: MemberContext::Trailer,
439            }
440        );
441    }
442
443    #[test]
444    fn exposes_the_spec_it_was_resolved_from() {
445        let spec = spec_of(vec![field("ClOrdID", 11)], vec![], vec![]);
446
447        let dictionary = spec.clone().resolve().unwrap();
448
449        assert_eq!(dictionary.spec(), &spec);
450        assert_eq!(dictionary.version(), spec.version);
451        assert_eq!(dictionary.fields(), spec.fields.as_slice());
452    }
453
454    #[test]
455    fn expands_components_in_place() {
456        let spec = spec_of(
457            vec![
458                field("ClOrdID", 11),
459                field("Commission", 12),
460                field("CommType", 13),
461                field("Text", 58),
462            ],
463            vec![component(
464                "CommissionData",
465                vec![field_ref(12, true), field_ref(13, true)],
466            )],
467            vec![message(
468                "NewOrderSingle",
469                vec![
470                    field_ref(11, true),
471                    component_ref("CommissionData", true),
472                    field_ref(58, false),
473                ],
474            )],
475        );
476
477        let dictionary = spec.resolve().unwrap();
478
479        let message = dictionary.messages().next().unwrap();
480        assert_eq!(
481            field_members(message.members()),
482            vec![
483                (Tag(11), true),
484                (Tag(12), true),
485                (Tag(13), true),
486                (Tag(58), false)
487            ]
488        );
489    }
490
491    #[test]
492    fn requiredness_combines_across_every_level() {
493        let spec = spec_of(
494            vec![field("Commission", 12), field("CommType", 13)],
495            vec![
496                component("Inner", vec![field_ref(12, true), field_ref(13, false)]),
497                component("Outer", vec![component_ref("Inner", true)]),
498            ],
499            vec![message(
500                "NewOrderSingle",
501                vec![component_ref("Outer", false)],
502            )],
503        );
504
505        let dictionary = spec.resolve().unwrap();
506
507        // An optional component makes everything below it optional.
508        let message = dictionary.messages().next().unwrap();
509        assert_eq!(
510            field_members(message.members()),
511            vec![(Tag(12), false), (Tag(13), false)]
512        );
513    }
514
515    #[test]
516    fn a_required_path_stays_required() {
517        let spec = spec_of(
518            vec![field("Commission", 12)],
519            vec![
520                component("Inner", vec![field_ref(12, true)]),
521                component("Outer", vec![component_ref("Inner", true)]),
522            ],
523            vec![message(
524                "NewOrderSingle",
525                vec![component_ref("Outer", true)],
526            )],
527        );
528
529        let dictionary = spec.resolve().unwrap();
530
531        let message = dictionary.messages().next().unwrap();
532        assert_eq!(field_members(message.members()), vec![(Tag(12), true)]);
533    }
534
535    #[test]
536    fn an_unknown_component_in_a_message_is_an_error() {
537        let spec = spec_of(
538            vec![],
539            vec![],
540            vec![message(
541                "NewOrderSingle",
542                vec![component_ref("Parties", false)],
543            )],
544        );
545
546        assert_eq!(
547            spec.resolve().unwrap_err(),
548            Error::UnknownComponent {
549                context: MemberContext::Message("NewOrderSingle".to_owned()),
550                component: "Parties".to_owned(),
551            }
552        );
553    }
554
555    #[test]
556    fn an_unknown_component_in_a_component_is_an_error() {
557        let spec = spec_of(
558            vec![],
559            vec![component("Outer", vec![component_ref("Inner", false)])],
560            vec![],
561        );
562
563        assert_eq!(
564            spec.resolve().unwrap_err(),
565            Error::UnknownComponent {
566                context: MemberContext::Component("Outer".to_owned()),
567                component: "Inner".to_owned(),
568            }
569        );
570    }
571
572    #[test]
573    fn an_unknown_tag_is_an_error() {
574        let spec = spec_of(
575            vec![],
576            vec![],
577            vec![message("Heartbeat", vec![field_ref(112, false)])],
578        );
579
580        assert_eq!(
581            spec.resolve().unwrap_err(),
582            Error::UnknownField {
583                context: MemberContext::Message("Heartbeat".to_owned()),
584                tag: Tag(112),
585            }
586        );
587    }
588
589    #[test]
590    fn a_self_referencing_component_is_an_error() {
591        let spec = spec_of(
592            vec![],
593            vec![component("Parties", vec![component_ref("Parties", false)])],
594            vec![],
595        );
596
597        assert_eq!(
598            spec.resolve().unwrap_err(),
599            Error::CircularComponent {
600                component: "Parties".to_owned(),
601            }
602        );
603    }
604
605    #[test]
606    fn mutually_referencing_components_are_an_error() {
607        let spec = spec_of(
608            vec![],
609            vec![
610                component(
611                    "Instrument",
612                    vec![component_ref("UnderlyingInstrument", false)],
613                ),
614                component(
615                    "UnderlyingInstrument",
616                    vec![component_ref("Instrument", false)],
617                ),
618            ],
619            vec![],
620        );
621
622        assert!(matches!(
623            spec.resolve().unwrap_err(),
624            Error::CircularComponent { .. }
625        ));
626    }
627
628    #[test]
629    fn an_unused_component_is_still_checked() {
630        // No message references the cycle; resolution must find it anyway.
631        let spec = spec_of(
632            vec![],
633            vec![component("Parties", vec![component_ref("Parties", false)])],
634            vec![message("Heartbeat", vec![])],
635        );
636
637        assert!(matches!(
638            spec.resolve().unwrap_err(),
639            Error::CircularComponent { .. }
640        ));
641    }
642
643    #[test]
644    fn a_diamond_of_empty_components_is_not_a_cycle() {
645        let spec = spec_of(
646            vec![],
647            vec![
648                component(
649                    "Top",
650                    vec![component_ref("Left", false), component_ref("Right", false)],
651                ),
652                component("Left", vec![component_ref("Bottom", false)]),
653                component("Right", vec![component_ref("Bottom", false)]),
654                component("Bottom", vec![]),
655            ],
656            vec![],
657        );
658
659        assert!(spec.resolve().is_ok());
660    }
661
662    #[test]
663    fn a_diamond_over_a_field_duplicates_the_tag() {
664        // Both arms of the diamond contribute tag 58 to Top's expansion.
665        let spec = spec_of(
666            vec![field("Text", 58)],
667            vec![
668                component(
669                    "Top",
670                    vec![component_ref("Left", false), component_ref("Right", false)],
671                ),
672                component("Left", vec![component_ref("Bottom", false)]),
673                component("Right", vec![component_ref("Bottom", false)]),
674                component("Bottom", vec![field_ref(58, false)]),
675            ],
676            vec![],
677        );
678
679        assert_eq!(
680            spec.resolve().unwrap_err(),
681            Error::DuplicateField {
682                tag: Tag(58),
683                first: MemberContext::Component("Top".to_owned()),
684                second: MemberContext::Component("Top".to_owned()),
685            }
686        );
687    }
688
689    #[test]
690    fn a_duplicate_tag_after_expansion_is_an_error() {
691        let spec = spec_of(
692            vec![field("Text", 58)],
693            vec![component("Notes", vec![field_ref(58, false)])],
694            vec![message(
695                "NewOrderSingle",
696                vec![field_ref(58, true), component_ref("Notes", false)],
697            )],
698        );
699
700        assert_eq!(
701            spec.resolve().unwrap_err(),
702            Error::DuplicateField {
703                tag: Tag(58),
704                first: MemberContext::Message("NewOrderSingle".to_owned()),
705                second: MemberContext::Message("NewOrderSingle".to_owned()),
706            }
707        );
708    }
709
710    #[test]
711    fn duplicate_component_definitions_are_an_error() {
712        let spec = spec_of(
713            vec![],
714            vec![component("Parties", vec![]), component("Parties", vec![])],
715            vec![],
716        );
717
718        assert_eq!(
719            spec.resolve().unwrap_err(),
720            Error::DuplicateComponent {
721                component: "Parties".to_owned(),
722            }
723        );
724    }
725
726    #[test]
727    fn duplicate_field_tags_are_an_error() {
728        let spec = spec_of(
729            vec![field("ClOrdID", 11), field("OrigClOrdID", 11)],
730            vec![],
731            vec![],
732        );
733
734        assert_eq!(
735            spec.resolve().unwrap_err(),
736            Error::DuplicateTag { tag: Tag(11) }
737        );
738    }
739
740    mod values {
741        use super::*;
742        use crate::EnumValue;
743
744        fn enum_field(data_type: DataType, values: &[&str]) -> Field {
745            Field {
746                name: "PartyRole".to_owned(),
747                tag: Tag(452),
748                data_type,
749                values: values
750                    .iter()
751                    .map(|value| EnumValue {
752                        value: (*value).to_owned(),
753                        description: format!("CODE_{value}"),
754                    })
755                    .collect(),
756            }
757        }
758
759        fn resolve(field: Field) -> Result<Dictionary, Error> {
760            spec_of(vec![field], vec![], vec![]).resolve()
761        }
762
763        #[test]
764        fn int_values_may_have_a_sign_and_leading_zeros() {
765            assert!(resolve(enum_field(DataType::Int, &["1", "-2", "007"])).is_ok());
766        }
767
768        #[test]
769        fn a_non_integer_value_of_an_int_field_is_an_error() {
770            assert_eq!(
771                resolve(enum_field(DataType::Int, &["1", "A"])).unwrap_err(),
772                Error::NonIntegerValue {
773                    field: "PartyRole".to_owned(),
774                    value: "A".to_owned(),
775                }
776            );
777        }
778
779        #[test]
780        fn every_int_based_type_is_checked() {
781            assert!(resolve(enum_field(DataType::NumInGroup, &["A"])).is_err());
782        }
783
784        #[test]
785        fn a_plus_sign_is_not_an_integer() {
786            assert!(resolve(enum_field(DataType::Int, &["+1"])).is_err());
787        }
788
789        #[test]
790        fn a_value_beyond_i64_is_not_an_integer() {
791            assert!(resolve(enum_field(DataType::Int, &["9223372036854775808"])).is_err());
792        }
793
794        #[test]
795        fn a_lone_minus_is_not_an_integer() {
796            assert!(resolve(enum_field(DataType::Int, &["-"])).is_err());
797        }
798
799        #[test]
800        fn a_repeated_code_is_an_error() {
801            assert_eq!(
802                resolve(enum_field(DataType::Char, &["1", "2", "1"])).unwrap_err(),
803                Error::RepeatedCode {
804                    field: "PartyRole".to_owned(),
805                    first: "1".to_owned(),
806                    second: "1".to_owned(),
807                }
808            );
809        }
810
811        #[test]
812        fn int_codes_repeat_by_number() {
813            assert_eq!(
814                resolve(enum_field(DataType::Int, &["1", "01"])).unwrap_err(),
815                Error::RepeatedCode {
816                    field: "PartyRole".to_owned(),
817                    first: "1".to_owned(),
818                    second: "01".to_owned(),
819                }
820            );
821        }
822
823        #[test]
824        fn values_of_other_types_are_not_checked() {
825            assert!(resolve(enum_field(DataType::Char, &["A"])).is_ok());
826        }
827    }
828
829    mod groups {
830        use super::*;
831
832        fn group(count_tag: u32, is_required: bool, members: Vec<spec::Member>) -> spec::Member {
833            spec::Member::Group(spec::Group {
834                count_tag: Tag(count_tag),
835                is_required,
836                members,
837            })
838        }
839
840        fn parties_fields() -> Vec<Field> {
841            vec![
842                field("NoPartyIDs", 453),
843                field("PartyID", 448),
844                field("PartyRole", 452),
845                field("PartyIDSource", 447),
846            ]
847        }
848
849        /// The group at `position` among a message's members.
850        fn group_at(message: Message<'_>, position: usize) -> Group<'_> {
851            match message.members().nth(position) {
852                Some(Member::Group(group)) => group,
853                other => panic!("expected a group, found {other:?}"),
854            }
855        }
856
857        fn nos_context() -> MemberContext {
858            MemberContext::Message("NewOrderSingle".to_owned())
859        }
860
861        #[test]
862        fn resolves_a_group_in_a_message() {
863            let spec = spec_of(
864                parties_fields(),
865                vec![],
866                vec![message(
867                    "NewOrderSingle",
868                    vec![group(
869                        453,
870                        false,
871                        vec![field_ref(448, false), field_ref(452, true)],
872                    )],
873                )],
874            );
875
876            let dictionary = spec.resolve().unwrap();
877
878            let group = group_at(dictionary.messages().next().unwrap(), 0);
879            assert_eq!(group.count_field().tag, Tag(453));
880            assert_eq!(group.delimiter().tag, Tag(448));
881            assert!(!group.is_required());
882            // The delimiter is required in every instance, whatever its flag.
883            assert_eq!(
884                field_members(group.members()),
885                vec![(Tag(448), true), (Tag(452), true)]
886            );
887        }
888
889        #[test]
890        fn requiredness_restarts_in_each_instance() {
891            let spec = spec_of(
892                parties_fields(),
893                vec![component(
894                    "Parties",
895                    vec![group(
896                        453,
897                        true,
898                        vec![
899                            field_ref(448, true),
900                            field_ref(452, false),
901                            field_ref(447, true),
902                        ],
903                    )],
904                )],
905                vec![message(
906                    "NewOrderSingle",
907                    vec![component_ref("Parties", false)],
908                )],
909            );
910
911            let dictionary = spec.resolve().unwrap();
912
913            // The optional component makes the group optional, but not the
914            // fields its instances require.
915            let group = group_at(dictionary.messages().next().unwrap(), 0);
916            assert!(!group.is_required());
917            assert_eq!(
918                field_members(group.members()),
919                vec![(Tag(448), true), (Tag(452), false), (Tag(447), true)]
920            );
921        }
922
923        #[test]
924        fn a_component_first_in_an_instance_becomes_required() {
925            let spec = spec_of(
926                vec![
927                    field("NoRelatedSym", 146),
928                    field("Symbol", 55),
929                    field("SecurityID", 48),
930                    field("Text", 58),
931                ],
932                vec![component(
933                    "Instrument",
934                    vec![field_ref(55, false), field_ref(48, true)],
935                )],
936                vec![message(
937                    "NewOrderSingle",
938                    vec![group(
939                        146,
940                        false,
941                        vec![component_ref("Instrument", false), field_ref(58, false)],
942                    )],
943                )],
944            );
945
946            let dictionary = spec.resolve().unwrap();
947
948            let group = group_at(dictionary.messages().next().unwrap(), 0);
949            assert_eq!(group.delimiter().tag, Tag(55));
950            assert_eq!(
951                field_members(group.members()),
952                vec![(Tag(55), true), (Tag(48), true), (Tag(58), false)]
953            );
954        }
955
956        #[test]
957        fn a_nested_group_first_in_an_instance_is_the_delimiter() {
958            let spec = spec_of(
959                vec![
960                    field("NoPartyIDs", 453),
961                    field("NoPartySubIDs", 802),
962                    field("PartySubID", 523),
963                ],
964                vec![],
965                vec![message(
966                    "NewOrderSingle",
967                    vec![group(
968                        453,
969                        false,
970                        vec![group(802, false, vec![field_ref(523, false)])],
971                    )],
972                )],
973            );
974
975            let dictionary = spec.resolve().unwrap();
976
977            let outer = group_at(dictionary.messages().next().unwrap(), 0);
978            assert_eq!(outer.delimiter().tag, Tag(802));
979            let Some(Member::Group(inner)) = outer.members().next() else {
980                panic!("expected a nested group");
981            };
982            assert!(inner.is_required());
983            assert_eq!(field_members(inner.members()), vec![(Tag(523), true)]);
984        }
985
986        #[test]
987        fn an_inline_group_is_declared_in_its_message() {
988            let spec = spec_of(
989                parties_fields(),
990                vec![],
991                vec![message(
992                    "NewOrderSingle",
993                    vec![group(453, false, vec![field_ref(448, false)])],
994                )],
995            );
996
997            let dictionary = spec.resolve().unwrap();
998
999            let group = group_at(dictionary.messages().next().unwrap(), 0);
1000            assert_eq!(group.declared_in(), &nos_context());
1001            assert_eq!(group.component(), None);
1002        }
1003
1004        #[test]
1005        fn a_group_making_up_a_component_takes_its_name() {
1006            let spec = spec_of(
1007                parties_fields(),
1008                vec![component(
1009                    "Parties",
1010                    vec![group(453, false, vec![field_ref(448, false)])],
1011                )],
1012                vec![message(
1013                    "NewOrderSingle",
1014                    vec![component_ref("Parties", false)],
1015                )],
1016            );
1017
1018            let dictionary = spec.resolve().unwrap();
1019
1020            let group = group_at(dictionary.messages().next().unwrap(), 0);
1021            assert_eq!(
1022                group.declared_in(),
1023                &MemberContext::Component("Parties".to_owned())
1024            );
1025            assert_eq!(group.component(), Some("Parties"));
1026        }
1027
1028        #[test]
1029        fn a_group_sharing_its_component_does_not_take_its_name() {
1030            let spec = spec_of(
1031                vec![
1032                    field("Symbol", 55),
1033                    field("NoSecurityAltID", 454),
1034                    field("SecurityAltID", 455),
1035                ],
1036                vec![component(
1037                    "Instrument",
1038                    vec![
1039                        field_ref(55, false),
1040                        group(454, false, vec![field_ref(455, false)]),
1041                    ],
1042                )],
1043                vec![message(
1044                    "NewOrderSingle",
1045                    vec![component_ref("Instrument", true)],
1046                )],
1047            );
1048
1049            let dictionary = spec.resolve().unwrap();
1050
1051            let group = group_at(dictionary.messages().next().unwrap(), 1);
1052            assert_eq!(
1053                group.declared_in(),
1054                &MemberContext::Component("Instrument".to_owned())
1055            );
1056            assert_eq!(group.component(), None);
1057        }
1058
1059        #[test]
1060        fn a_nested_group_is_declared_in_its_own_component() {
1061            let spec = spec_of(
1062                vec![
1063                    field("NoPartyIDs", 453),
1064                    field("PartyID", 448),
1065                    field("NoPartySubIDs", 802),
1066                    field("PartySubID", 523),
1067                ],
1068                vec![
1069                    component(
1070                        "PtysSubGrp",
1071                        vec![group(802, false, vec![field_ref(523, false)])],
1072                    ),
1073                    component(
1074                        "Parties",
1075                        vec![group(
1076                            453,
1077                            false,
1078                            vec![field_ref(448, false), component_ref("PtysSubGrp", false)],
1079                        )],
1080                    ),
1081                ],
1082                vec![message(
1083                    "NewOrderSingle",
1084                    vec![component_ref("Parties", false)],
1085                )],
1086            );
1087
1088            let dictionary = spec.resolve().unwrap();
1089
1090            let parties = group_at(dictionary.messages().next().unwrap(), 0);
1091            let Some(Member::Group(sub_ids)) = parties.members().nth(1) else {
1092                panic!("expected a nested group");
1093            };
1094            assert_eq!(
1095                sub_ids.declared_in(),
1096                &MemberContext::Component("PtysSubGrp".to_owned())
1097            );
1098            assert_eq!(sub_ids.component(), Some("PtysSubGrp"));
1099        }
1100
1101        #[test]
1102        fn a_component_wrapping_a_component_does_not_claim_its_group() {
1103            let spec = spec_of(
1104                parties_fields(),
1105                vec![
1106                    component(
1107                        "Inner",
1108                        vec![group(453, false, vec![field_ref(448, false)])],
1109                    ),
1110                    component("Outer", vec![component_ref("Inner", false)]),
1111                ],
1112                vec![message(
1113                    "NewOrderSingle",
1114                    vec![component_ref("Outer", false)],
1115                )],
1116            );
1117
1118            let dictionary = spec.resolve().unwrap();
1119
1120            let group = group_at(dictionary.messages().next().unwrap(), 0);
1121            assert_eq!(group.component(), Some("Inner"));
1122        }
1123
1124        #[test]
1125        fn an_empty_group_is_an_error() {
1126            let spec = spec_of(
1127                parties_fields(),
1128                vec![],
1129                vec![message("NewOrderSingle", vec![group(453, false, vec![])])],
1130            );
1131
1132            assert_eq!(
1133                spec.resolve().unwrap_err(),
1134                Error::EmptyGroup {
1135                    context: nos_context().group("NoPartyIDs"),
1136                }
1137            );
1138        }
1139
1140        #[test]
1141        fn a_group_of_an_empty_component_is_an_error() {
1142            let spec = spec_of(
1143                parties_fields(),
1144                vec![component("Nothing", vec![])],
1145                vec![message(
1146                    "NewOrderSingle",
1147                    vec![group(453, false, vec![component_ref("Nothing", true)])],
1148                )],
1149            );
1150
1151            assert_eq!(
1152                spec.resolve().unwrap_err(),
1153                Error::EmptyGroup {
1154                    context: nos_context().group("NoPartyIDs"),
1155                }
1156            );
1157        }
1158
1159        #[test]
1160        fn an_unknown_count_tag_is_an_error() {
1161            let spec = spec_of(
1162                vec![field("PartyID", 448)],
1163                vec![],
1164                vec![message(
1165                    "NewOrderSingle",
1166                    vec![group(453, false, vec![field_ref(448, false)])],
1167                )],
1168            );
1169
1170            assert_eq!(
1171                spec.resolve().unwrap_err(),
1172                Error::UnknownField {
1173                    context: nos_context(),
1174                    tag: Tag(453),
1175                }
1176            );
1177        }
1178
1179        #[test]
1180        fn a_cycle_through_a_group_is_an_error() {
1181            let spec = spec_of(
1182                parties_fields(),
1183                vec![component(
1184                    "Parties",
1185                    vec![group(453, false, vec![component_ref("Parties", false)])],
1186                )],
1187                vec![],
1188            );
1189
1190            assert_eq!(
1191                spec.resolve().unwrap_err(),
1192                Error::CircularComponent {
1193                    component: "Parties".to_owned(),
1194                }
1195            );
1196        }
1197
1198        #[test]
1199        fn a_tag_in_a_scope_and_in_its_group_is_an_error() {
1200            let spec = spec_of(
1201                parties_fields(),
1202                vec![],
1203                vec![message(
1204                    "NewOrderSingle",
1205                    vec![
1206                        field_ref(448, false),
1207                        group(453, false, vec![field_ref(448, false)]),
1208                    ],
1209                )],
1210            );
1211
1212            assert_eq!(
1213                spec.resolve().unwrap_err(),
1214                Error::DuplicateField {
1215                    tag: Tag(448),
1216                    first: nos_context(),
1217                    second: nos_context().group("NoPartyIDs"),
1218                }
1219            );
1220        }
1221
1222        #[test]
1223        fn a_count_tag_also_used_as_a_field_is_an_error() {
1224            let spec = spec_of(
1225                parties_fields(),
1226                vec![],
1227                vec![message(
1228                    "NewOrderSingle",
1229                    vec![
1230                        field_ref(453, false),
1231                        group(453, false, vec![field_ref(448, false)]),
1232                    ],
1233                )],
1234            );
1235
1236            assert_eq!(
1237                spec.resolve().unwrap_err(),
1238                Error::DuplicateField {
1239                    tag: Tag(453),
1240                    first: nos_context(),
1241                    second: nos_context(),
1242                }
1243            );
1244        }
1245
1246        #[test]
1247        fn sibling_groups_sharing_a_tag_are_an_error() {
1248            let mut fields = parties_fields();
1249            fields.push(field("NoNestedPartyIDs", 539));
1250            let spec = spec_of(
1251                fields,
1252                vec![],
1253                vec![message(
1254                    "NewOrderSingle",
1255                    vec![
1256                        group(453, false, vec![field_ref(448, false)]),
1257                        group(539, false, vec![field_ref(448, false)]),
1258                    ],
1259                )],
1260            );
1261
1262            assert_eq!(
1263                spec.resolve().unwrap_err(),
1264                Error::DuplicateField {
1265                    tag: Tag(448),
1266                    first: nos_context().group("NoPartyIDs"),
1267                    second: nos_context().group("NoNestedPartyIDs"),
1268                }
1269            );
1270        }
1271
1272        #[test]
1273        fn a_duplicate_within_an_instance_names_the_instance() {
1274            let spec = spec_of(
1275                parties_fields(),
1276                vec![],
1277                vec![message(
1278                    "NewOrderSingle",
1279                    vec![group(
1280                        453,
1281                        false,
1282                        vec![field_ref(448, false), field_ref(448, false)],
1283                    )],
1284                )],
1285            );
1286
1287            assert_eq!(
1288                spec.resolve().unwrap_err(),
1289                Error::DuplicateField {
1290                    tag: Tag(448),
1291                    first: nos_context().group("NoPartyIDs"),
1292                    second: nos_context().group("NoPartyIDs"),
1293                }
1294            );
1295        }
1296    }
1297}