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            length_tag: None,
242            values: vec![],
243        }
244    }
245
246    fn field_ref(tag: u32, is_required: bool) -> spec::Member {
247        spec::Member::Field(FieldRef {
248            tag: Tag(tag),
249            is_required,
250        })
251    }
252
253    /// Members as (tag, is_required), for member lists without groups.
254    fn field_members<'a>(members: impl Iterator<Item = Member<'a>>) -> Vec<(Tag, bool)> {
255        members
256            .map(|member| match member {
257                Member::Field { field, is_required } => (field.tag, is_required),
258                Member::Group(group) => panic!("unexpected group {}", group.count_field().name),
259            })
260            .collect()
261    }
262
263    fn component_ref(name: &str, is_required: bool) -> spec::Member {
264        spec::Member::Component(ComponentRef {
265            name: name.to_owned(),
266            is_required,
267        })
268    }
269
270    fn component(name: &str, members: Vec<spec::Member>) -> Component {
271        Component {
272            name: name.to_owned(),
273            members,
274        }
275    }
276
277    fn message(name: &str, members: Vec<spec::Member>) -> spec::Message {
278        spec::Message {
279            name: name.to_owned(),
280            msg_type: "D".to_owned(),
281            members,
282            category: Category::App,
283        }
284    }
285
286    fn spec_of(
287        fields: Vec<Field>,
288        components: Vec<Component>,
289        messages: Vec<spec::Message>,
290    ) -> Spec {
291        Spec {
292            version: Version {
293                protocol: Protocol::Fix,
294                major: 4,
295                minor: 4,
296                service_pack: 0,
297            },
298            header: vec![],
299            trailer: vec![],
300            messages,
301            fields,
302            components,
303        }
304    }
305
306    #[test]
307    fn resolves_direct_field_references() {
308        let spec = spec_of(
309            vec![field("ClOrdID", 11), field("Text", 58)],
310            vec![],
311            vec![message(
312                "NewOrderSingle",
313                vec![field_ref(11, true), field_ref(58, false)],
314            )],
315        );
316
317        let dictionary = spec.resolve().unwrap();
318
319        let messages: Vec<Message> = dictionary.messages().collect();
320        assert_eq!(messages.len(), 1);
321        assert_eq!(messages[0].name(), "NewOrderSingle");
322        assert_eq!(messages[0].msg_type(), "D");
323        assert_eq!(messages[0].category(), Category::App);
324        assert_eq!(
325            messages[0].members().collect::<Vec<Member>>(),
326            vec![
327                Member::Field {
328                    field: &dictionary.fields()[0],
329                    is_required: true,
330                },
331                Member::Field {
332                    field: &dictionary.fields()[1],
333                    is_required: false,
334                },
335            ]
336        );
337    }
338
339    #[test]
340    fn resolves_the_header_and_trailer() {
341        let mut spec = spec_of(
342            vec![
343                field("SenderCompID", 49),
344                field("TargetCompID", 56),
345                field("CheckSum", 10),
346            ],
347            vec![component("Target", vec![field_ref(56, true)])],
348            vec![],
349        );
350        spec.header = vec![field_ref(49, true), component_ref("Target", false)];
351        spec.trailer = vec![field_ref(10, true)];
352
353        let dictionary = spec.resolve().unwrap();
354
355        assert_eq!(
356            field_members(dictionary.header()),
357            [(Tag(49), true), (Tag(56), false)]
358        );
359        assert_eq!(field_members(dictionary.trailer()), [(Tag(10), true)]);
360    }
361
362    #[test]
363    fn a_header_group_is_declared_in_the_header() {
364        let mut spec = spec_of(
365            vec![field("NoHops", 627), field("HopCompID", 628)],
366            vec![],
367            vec![],
368        );
369        spec.header = vec![spec::Member::Group(spec::Group {
370            count_tag: Tag(627),
371            is_required: false,
372            members: vec![field_ref(628, false)],
373        })];
374
375        let dictionary = spec.resolve().unwrap();
376
377        let Some(Member::Group(hops)) = dictionary.header().next() else {
378            panic!("expected the hops group");
379        };
380        assert_eq!(hops.declared_in(), &MemberContext::Header);
381    }
382
383    #[test]
384    fn a_header_tag_in_a_message_is_an_error() {
385        let mut spec = spec_of(
386            vec![field("ClOrdID", 11), field("SenderCompID", 49)],
387            vec![],
388            vec![message(
389                "NewOrderSingle",
390                vec![field_ref(11, true), field_ref(49, false)],
391            )],
392        );
393        spec.header = vec![field_ref(49, true)];
394
395        let error = spec.resolve().unwrap_err();
396
397        assert_eq!(
398            error,
399            Error::DuplicateField {
400                tag: Tag(49),
401                first: MemberContext::Header,
402                second: MemberContext::Message("NewOrderSingle".to_owned()),
403            }
404        );
405        assert_eq!(
406            error.to_string(),
407            "tag 49 appears in both the header and message 'NewOrderSingle'"
408        );
409    }
410
411    #[test]
412    fn a_trailer_tag_in_a_message_is_an_error() {
413        let mut spec = spec_of(
414            vec![field("Signature", 89)],
415            vec![],
416            vec![message("NewOrderSingle", vec![field_ref(89, false)])],
417        );
418        spec.trailer = vec![field_ref(89, false)];
419
420        assert_eq!(
421            spec.resolve().unwrap_err(),
422            Error::DuplicateField {
423                tag: Tag(89),
424                first: MemberContext::Message("NewOrderSingle".to_owned()),
425                second: MemberContext::Trailer,
426            }
427        );
428    }
429
430    #[test]
431    fn an_unknown_trailer_field_names_the_trailer() {
432        let mut spec = spec_of(vec![], vec![], vec![]);
433        spec.trailer = vec![field_ref(10, true)];
434
435        assert_eq!(
436            spec.resolve().unwrap_err(),
437            Error::UnknownField {
438                tag: Tag(10),
439                context: MemberContext::Trailer,
440            }
441        );
442    }
443
444    #[test]
445    fn exposes_the_spec_it_was_resolved_from() {
446        let spec = spec_of(vec![field("ClOrdID", 11)], vec![], vec![]);
447
448        let dictionary = spec.clone().resolve().unwrap();
449
450        assert_eq!(dictionary.spec(), &spec);
451        assert_eq!(dictionary.version(), spec.version);
452        assert_eq!(dictionary.fields(), spec.fields.as_slice());
453    }
454
455    #[test]
456    fn expands_components_in_place() {
457        let spec = spec_of(
458            vec![
459                field("ClOrdID", 11),
460                field("Commission", 12),
461                field("CommType", 13),
462                field("Text", 58),
463            ],
464            vec![component(
465                "CommissionData",
466                vec![field_ref(12, true), field_ref(13, true)],
467            )],
468            vec![message(
469                "NewOrderSingle",
470                vec![
471                    field_ref(11, true),
472                    component_ref("CommissionData", true),
473                    field_ref(58, false),
474                ],
475            )],
476        );
477
478        let dictionary = spec.resolve().unwrap();
479
480        let message = dictionary.messages().next().unwrap();
481        assert_eq!(
482            field_members(message.members()),
483            vec![
484                (Tag(11), true),
485                (Tag(12), true),
486                (Tag(13), true),
487                (Tag(58), false)
488            ]
489        );
490    }
491
492    #[test]
493    fn requiredness_combines_across_every_level() {
494        let spec = spec_of(
495            vec![field("Commission", 12), field("CommType", 13)],
496            vec![
497                component("Inner", vec![field_ref(12, true), field_ref(13, false)]),
498                component("Outer", vec![component_ref("Inner", true)]),
499            ],
500            vec![message(
501                "NewOrderSingle",
502                vec![component_ref("Outer", false)],
503            )],
504        );
505
506        let dictionary = spec.resolve().unwrap();
507
508        // An optional component makes everything below it optional.
509        let message = dictionary.messages().next().unwrap();
510        assert_eq!(
511            field_members(message.members()),
512            vec![(Tag(12), false), (Tag(13), false)]
513        );
514    }
515
516    #[test]
517    fn a_required_path_stays_required() {
518        let spec = spec_of(
519            vec![field("Commission", 12)],
520            vec![
521                component("Inner", vec![field_ref(12, true)]),
522                component("Outer", vec![component_ref("Inner", true)]),
523            ],
524            vec![message(
525                "NewOrderSingle",
526                vec![component_ref("Outer", true)],
527            )],
528        );
529
530        let dictionary = spec.resolve().unwrap();
531
532        let message = dictionary.messages().next().unwrap();
533        assert_eq!(field_members(message.members()), vec![(Tag(12), true)]);
534    }
535
536    #[test]
537    fn an_unknown_component_in_a_message_is_an_error() {
538        let spec = spec_of(
539            vec![],
540            vec![],
541            vec![message(
542                "NewOrderSingle",
543                vec![component_ref("Parties", false)],
544            )],
545        );
546
547        assert_eq!(
548            spec.resolve().unwrap_err(),
549            Error::UnknownComponent {
550                context: MemberContext::Message("NewOrderSingle".to_owned()),
551                component: "Parties".to_owned(),
552            }
553        );
554    }
555
556    #[test]
557    fn an_unknown_component_in_a_component_is_an_error() {
558        let spec = spec_of(
559            vec![],
560            vec![component("Outer", vec![component_ref("Inner", false)])],
561            vec![],
562        );
563
564        assert_eq!(
565            spec.resolve().unwrap_err(),
566            Error::UnknownComponent {
567                context: MemberContext::Component("Outer".to_owned()),
568                component: "Inner".to_owned(),
569            }
570        );
571    }
572
573    #[test]
574    fn an_unknown_tag_is_an_error() {
575        let spec = spec_of(
576            vec![],
577            vec![],
578            vec![message("Heartbeat", vec![field_ref(112, false)])],
579        );
580
581        assert_eq!(
582            spec.resolve().unwrap_err(),
583            Error::UnknownField {
584                context: MemberContext::Message("Heartbeat".to_owned()),
585                tag: Tag(112),
586            }
587        );
588    }
589
590    #[test]
591    fn a_self_referencing_component_is_an_error() {
592        let spec = spec_of(
593            vec![],
594            vec![component("Parties", vec![component_ref("Parties", false)])],
595            vec![],
596        );
597
598        assert_eq!(
599            spec.resolve().unwrap_err(),
600            Error::CircularComponent {
601                component: "Parties".to_owned(),
602            }
603        );
604    }
605
606    #[test]
607    fn mutually_referencing_components_are_an_error() {
608        let spec = spec_of(
609            vec![],
610            vec![
611                component(
612                    "Instrument",
613                    vec![component_ref("UnderlyingInstrument", false)],
614                ),
615                component(
616                    "UnderlyingInstrument",
617                    vec![component_ref("Instrument", false)],
618                ),
619            ],
620            vec![],
621        );
622
623        assert!(matches!(
624            spec.resolve().unwrap_err(),
625            Error::CircularComponent { .. }
626        ));
627    }
628
629    #[test]
630    fn an_unused_component_is_still_checked() {
631        // No message references the cycle; resolution must find it anyway.
632        let spec = spec_of(
633            vec![],
634            vec![component("Parties", vec![component_ref("Parties", false)])],
635            vec![message("Heartbeat", vec![])],
636        );
637
638        assert!(matches!(
639            spec.resolve().unwrap_err(),
640            Error::CircularComponent { .. }
641        ));
642    }
643
644    #[test]
645    fn a_diamond_of_empty_components_is_not_a_cycle() {
646        let spec = spec_of(
647            vec![],
648            vec![
649                component(
650                    "Top",
651                    vec![component_ref("Left", false), component_ref("Right", false)],
652                ),
653                component("Left", vec![component_ref("Bottom", false)]),
654                component("Right", vec![component_ref("Bottom", false)]),
655                component("Bottom", vec![]),
656            ],
657            vec![],
658        );
659
660        assert!(spec.resolve().is_ok());
661    }
662
663    #[test]
664    fn a_diamond_over_a_field_duplicates_the_tag() {
665        // Both arms of the diamond contribute tag 58 to Top's expansion.
666        let spec = spec_of(
667            vec![field("Text", 58)],
668            vec![
669                component(
670                    "Top",
671                    vec![component_ref("Left", false), component_ref("Right", false)],
672                ),
673                component("Left", vec![component_ref("Bottom", false)]),
674                component("Right", vec![component_ref("Bottom", false)]),
675                component("Bottom", vec![field_ref(58, false)]),
676            ],
677            vec![],
678        );
679
680        assert_eq!(
681            spec.resolve().unwrap_err(),
682            Error::DuplicateField {
683                tag: Tag(58),
684                first: MemberContext::Component("Top".to_owned()),
685                second: MemberContext::Component("Top".to_owned()),
686            }
687        );
688    }
689
690    #[test]
691    fn a_duplicate_tag_after_expansion_is_an_error() {
692        let spec = spec_of(
693            vec![field("Text", 58)],
694            vec![component("Notes", vec![field_ref(58, false)])],
695            vec![message(
696                "NewOrderSingle",
697                vec![field_ref(58, true), component_ref("Notes", false)],
698            )],
699        );
700
701        assert_eq!(
702            spec.resolve().unwrap_err(),
703            Error::DuplicateField {
704                tag: Tag(58),
705                first: MemberContext::Message("NewOrderSingle".to_owned()),
706                second: MemberContext::Message("NewOrderSingle".to_owned()),
707            }
708        );
709    }
710
711    #[test]
712    fn duplicate_component_definitions_are_an_error() {
713        let spec = spec_of(
714            vec![],
715            vec![component("Parties", vec![]), component("Parties", vec![])],
716            vec![],
717        );
718
719        assert_eq!(
720            spec.resolve().unwrap_err(),
721            Error::DuplicateComponent {
722                component: "Parties".to_owned(),
723            }
724        );
725    }
726
727    #[test]
728    fn messages_sharing_a_msg_type_are_an_error() {
729        let spec = spec_of(
730            vec![],
731            vec![],
732            vec![
733                message("NewOrderSingle", vec![]),
734                message("NewOrderCross", vec![]),
735            ],
736        );
737
738        assert_eq!(
739            spec.resolve().unwrap_err(),
740            Error::DuplicateMsgType {
741                msg_type: "D".to_owned(),
742                first: "NewOrderSingle".to_owned(),
743                second: "NewOrderCross".to_owned(),
744            }
745        );
746    }
747
748    #[test]
749    fn duplicate_field_tags_are_an_error() {
750        let spec = spec_of(
751            vec![field("ClOrdID", 11), field("OrigClOrdID", 11)],
752            vec![],
753            vec![],
754        );
755
756        assert_eq!(
757            spec.resolve().unwrap_err(),
758            Error::DuplicateTag { tag: Tag(11) }
759        );
760    }
761
762    mod values {
763        use super::*;
764        use crate::EnumValue;
765
766        fn enum_field(data_type: DataType, values: &[&str]) -> Field {
767            Field {
768                name: "PartyRole".to_owned(),
769                tag: Tag(452),
770                data_type,
771                length_tag: None,
772                values: values
773                    .iter()
774                    .map(|value| EnumValue {
775                        value: (*value).to_owned(),
776                        description: format!("CODE_{value}"),
777                    })
778                    .collect(),
779            }
780        }
781
782        fn resolve(field: Field) -> Result<Dictionary, Error> {
783            spec_of(vec![field], vec![], vec![]).resolve()
784        }
785
786        #[test]
787        fn int_values_may_have_a_sign_and_leading_zeros() {
788            assert!(resolve(enum_field(DataType::Int, &["1", "-2", "007"])).is_ok());
789        }
790
791        #[test]
792        fn a_non_integer_value_of_an_int_field_is_an_error() {
793            assert_eq!(
794                resolve(enum_field(DataType::Int, &["1", "A"])).unwrap_err(),
795                Error::NonIntegerValue {
796                    field: "PartyRole".to_owned(),
797                    value: "A".to_owned(),
798                }
799            );
800        }
801
802        #[test]
803        fn every_int_based_type_is_checked() {
804            assert!(resolve(enum_field(DataType::NumInGroup, &["A"])).is_err());
805        }
806
807        #[test]
808        fn a_plus_sign_is_not_an_integer() {
809            assert!(resolve(enum_field(DataType::Int, &["+1"])).is_err());
810        }
811
812        #[test]
813        fn a_value_beyond_i64_is_not_an_integer() {
814            assert!(resolve(enum_field(DataType::Int, &["9223372036854775808"])).is_err());
815        }
816
817        #[test]
818        fn a_lone_minus_is_not_an_integer() {
819            assert!(resolve(enum_field(DataType::Int, &["-"])).is_err());
820        }
821
822        #[test]
823        fn a_repeated_code_is_an_error() {
824            assert_eq!(
825                resolve(enum_field(DataType::Char, &["1", "2", "1"])).unwrap_err(),
826                Error::RepeatedCode {
827                    field: "PartyRole".to_owned(),
828                    first: "1".to_owned(),
829                    second: "1".to_owned(),
830                }
831            );
832        }
833
834        #[test]
835        fn int_codes_repeat_by_number() {
836            assert_eq!(
837                resolve(enum_field(DataType::Int, &["1", "01"])).unwrap_err(),
838                Error::RepeatedCode {
839                    field: "PartyRole".to_owned(),
840                    first: "1".to_owned(),
841                    second: "01".to_owned(),
842                }
843            );
844        }
845
846        #[test]
847        fn values_of_other_types_are_not_checked() {
848            assert!(resolve(enum_field(DataType::Char, &["A"])).is_ok());
849        }
850    }
851
852    mod length_tags {
853        use super::*;
854
855        fn typed(name: &str, tag: u32, data_type: DataType) -> Field {
856            Field {
857                data_type,
858                ..field(name, tag)
859            }
860        }
861
862        fn data(name: &str, tag: u32, length_tag: u32) -> Field {
863            Field {
864                length_tag: Some(Tag(length_tag)),
865                ..typed(name, tag, DataType::Data)
866            }
867        }
868
869        fn resolve(fields: Vec<Field>) -> Result<Dictionary, Error> {
870            spec_of(fields, vec![], vec![]).resolve()
871        }
872
873        #[test]
874        fn a_data_field_takes_its_length_from_a_length_field() {
875            let fields = vec![
876                typed("RawDataLength", 95, DataType::Length),
877                data("RawData", 96, 95),
878            ];
879
880            assert!(resolve(fields).is_ok());
881        }
882
883        #[test]
884        fn an_xml_data_field_takes_its_length_from_a_length_field() {
885            let fields = vec![
886                typed("XmlDataLen", 212, DataType::Length),
887                Field {
888                    data_type: DataType::XmlData,
889                    ..data("XmlData", 213, 212)
890                },
891            ];
892
893            assert!(resolve(fields).is_ok());
894        }
895
896        #[test]
897        fn a_length_tag_on_another_type_is_an_error() {
898            let fields = vec![
899                typed("RawDataLength", 95, DataType::Length),
900                Field {
901                    length_tag: Some(Tag(95)),
902                    ..field("Text", 58)
903                },
904            ];
905
906            assert_eq!(
907                resolve(fields).unwrap_err(),
908                Error::UnexpectedLengthTag {
909                    field: "Text".to_owned(),
910                    tag: Tag(95),
911                }
912            );
913        }
914
915        #[test]
916        fn an_unknown_length_tag_is_an_error() {
917            assert_eq!(
918                resolve(vec![data("RawData", 96, 95)]).unwrap_err(),
919                Error::UnknownLengthTag {
920                    field: "RawData".to_owned(),
921                    tag: Tag(95),
922                }
923            );
924        }
925
926        #[test]
927        fn a_length_field_of_another_type_is_an_error() {
928            let fields = vec![
929                typed("RawDataLength", 95, DataType::Int),
930                data("RawData", 96, 95),
931            ];
932
933            assert_eq!(
934                resolve(fields).unwrap_err(),
935                Error::NonLengthField {
936                    field: "RawData".to_owned(),
937                    length_field: "RawDataLength".to_owned(),
938                }
939            );
940        }
941
942        #[test]
943        fn data_fields_sharing_a_length_field_are_an_error() {
944            let fields = vec![
945                typed("RawDataLength", 95, DataType::Length),
946                data("RawData", 96, 95),
947                data("SecureData", 91, 95),
948            ];
949
950            assert_eq!(
951                resolve(fields).unwrap_err(),
952                Error::SharedLengthField {
953                    length_field: "RawDataLength".to_owned(),
954                    first: "RawData".to_owned(),
955                    second: "SecureData".to_owned(),
956                }
957            );
958        }
959
960        #[test]
961        fn a_used_data_field_without_a_length_tag_is_an_error() {
962            let spec = spec_of(
963                vec![typed("RawData", 96, DataType::Data)],
964                vec![],
965                vec![message("News", vec![field_ref(96, false)])],
966            );
967
968            assert_eq!(
969                spec.resolve().unwrap_err(),
970                Error::MissingLengthTag {
971                    field: "RawData".to_owned(),
972                    context: MemberContext::Message("News".to_owned()),
973                }
974            );
975        }
976
977        #[test]
978        fn an_unused_data_field_needs_no_length_tag() {
979            assert!(resolve(vec![typed("RawData", 96, DataType::Data)]).is_ok());
980        }
981    }
982
983    mod groups {
984        use super::*;
985
986        fn group(count_tag: u32, is_required: bool, members: Vec<spec::Member>) -> spec::Member {
987            spec::Member::Group(spec::Group {
988                count_tag: Tag(count_tag),
989                is_required,
990                members,
991            })
992        }
993
994        fn parties_fields() -> Vec<Field> {
995            vec![
996                field("NoPartyIDs", 453),
997                field("PartyID", 448),
998                field("PartyRole", 452),
999                field("PartyIDSource", 447),
1000            ]
1001        }
1002
1003        /// The group at `position` among a message's members.
1004        fn group_at(message: Message<'_>, position: usize) -> Group<'_> {
1005            match message.members().nth(position) {
1006                Some(Member::Group(group)) => group,
1007                other => panic!("expected a group, found {other:?}"),
1008            }
1009        }
1010
1011        fn nos_context() -> MemberContext {
1012            MemberContext::Message("NewOrderSingle".to_owned())
1013        }
1014
1015        #[test]
1016        fn resolves_a_group_in_a_message() {
1017            let spec = spec_of(
1018                parties_fields(),
1019                vec![],
1020                vec![message(
1021                    "NewOrderSingle",
1022                    vec![group(
1023                        453,
1024                        false,
1025                        vec![field_ref(448, false), field_ref(452, true)],
1026                    )],
1027                )],
1028            );
1029
1030            let dictionary = spec.resolve().unwrap();
1031
1032            let group = group_at(dictionary.messages().next().unwrap(), 0);
1033            assert_eq!(group.count_field().tag, Tag(453));
1034            assert_eq!(group.delimiter().tag, Tag(448));
1035            assert!(!group.is_required());
1036            // The delimiter is required in every instance, whatever its flag.
1037            assert_eq!(
1038                field_members(group.members()),
1039                vec![(Tag(448), true), (Tag(452), true)]
1040            );
1041        }
1042
1043        #[test]
1044        fn requiredness_restarts_in_each_instance() {
1045            let spec = spec_of(
1046                parties_fields(),
1047                vec![component(
1048                    "Parties",
1049                    vec![group(
1050                        453,
1051                        true,
1052                        vec![
1053                            field_ref(448, true),
1054                            field_ref(452, false),
1055                            field_ref(447, true),
1056                        ],
1057                    )],
1058                )],
1059                vec![message(
1060                    "NewOrderSingle",
1061                    vec![component_ref("Parties", false)],
1062                )],
1063            );
1064
1065            let dictionary = spec.resolve().unwrap();
1066
1067            // The optional component makes the group optional, but not the
1068            // fields its instances require.
1069            let group = group_at(dictionary.messages().next().unwrap(), 0);
1070            assert!(!group.is_required());
1071            assert_eq!(
1072                field_members(group.members()),
1073                vec![(Tag(448), true), (Tag(452), false), (Tag(447), true)]
1074            );
1075        }
1076
1077        #[test]
1078        fn a_component_first_in_an_instance_becomes_required() {
1079            let spec = spec_of(
1080                vec![
1081                    field("NoRelatedSym", 146),
1082                    field("Symbol", 55),
1083                    field("SecurityID", 48),
1084                    field("Text", 58),
1085                ],
1086                vec![component(
1087                    "Instrument",
1088                    vec![field_ref(55, false), field_ref(48, true)],
1089                )],
1090                vec![message(
1091                    "NewOrderSingle",
1092                    vec![group(
1093                        146,
1094                        false,
1095                        vec![component_ref("Instrument", false), field_ref(58, false)],
1096                    )],
1097                )],
1098            );
1099
1100            let dictionary = spec.resolve().unwrap();
1101
1102            let group = group_at(dictionary.messages().next().unwrap(), 0);
1103            assert_eq!(group.delimiter().tag, Tag(55));
1104            assert_eq!(
1105                field_members(group.members()),
1106                vec![(Tag(55), true), (Tag(48), true), (Tag(58), false)]
1107            );
1108        }
1109
1110        #[test]
1111        fn a_nested_group_first_in_an_instance_is_the_delimiter() {
1112            let spec = spec_of(
1113                vec![
1114                    field("NoPartyIDs", 453),
1115                    field("NoPartySubIDs", 802),
1116                    field("PartySubID", 523),
1117                ],
1118                vec![],
1119                vec![message(
1120                    "NewOrderSingle",
1121                    vec![group(
1122                        453,
1123                        false,
1124                        vec![group(802, false, vec![field_ref(523, false)])],
1125                    )],
1126                )],
1127            );
1128
1129            let dictionary = spec.resolve().unwrap();
1130
1131            let outer = group_at(dictionary.messages().next().unwrap(), 0);
1132            assert_eq!(outer.delimiter().tag, Tag(802));
1133            let Some(Member::Group(inner)) = outer.members().next() else {
1134                panic!("expected a nested group");
1135            };
1136            assert!(inner.is_required());
1137            assert_eq!(field_members(inner.members()), vec![(Tag(523), true)]);
1138        }
1139
1140        #[test]
1141        fn an_inline_group_is_declared_in_its_message() {
1142            let spec = spec_of(
1143                parties_fields(),
1144                vec![],
1145                vec![message(
1146                    "NewOrderSingle",
1147                    vec![group(453, false, vec![field_ref(448, false)])],
1148                )],
1149            );
1150
1151            let dictionary = spec.resolve().unwrap();
1152
1153            let group = group_at(dictionary.messages().next().unwrap(), 0);
1154            assert_eq!(group.declared_in(), &nos_context());
1155            assert_eq!(group.component(), None);
1156        }
1157
1158        #[test]
1159        fn a_group_making_up_a_component_takes_its_name() {
1160            let spec = spec_of(
1161                parties_fields(),
1162                vec![component(
1163                    "Parties",
1164                    vec![group(453, false, vec![field_ref(448, false)])],
1165                )],
1166                vec![message(
1167                    "NewOrderSingle",
1168                    vec![component_ref("Parties", false)],
1169                )],
1170            );
1171
1172            let dictionary = spec.resolve().unwrap();
1173
1174            let group = group_at(dictionary.messages().next().unwrap(), 0);
1175            assert_eq!(
1176                group.declared_in(),
1177                &MemberContext::Component("Parties".to_owned())
1178            );
1179            assert_eq!(group.component(), Some("Parties"));
1180        }
1181
1182        #[test]
1183        fn a_group_sharing_its_component_does_not_take_its_name() {
1184            let spec = spec_of(
1185                vec![
1186                    field("Symbol", 55),
1187                    field("NoSecurityAltID", 454),
1188                    field("SecurityAltID", 455),
1189                ],
1190                vec![component(
1191                    "Instrument",
1192                    vec![
1193                        field_ref(55, false),
1194                        group(454, false, vec![field_ref(455, false)]),
1195                    ],
1196                )],
1197                vec![message(
1198                    "NewOrderSingle",
1199                    vec![component_ref("Instrument", true)],
1200                )],
1201            );
1202
1203            let dictionary = spec.resolve().unwrap();
1204
1205            let group = group_at(dictionary.messages().next().unwrap(), 1);
1206            assert_eq!(
1207                group.declared_in(),
1208                &MemberContext::Component("Instrument".to_owned())
1209            );
1210            assert_eq!(group.component(), None);
1211        }
1212
1213        #[test]
1214        fn a_nested_group_is_declared_in_its_own_component() {
1215            let spec = spec_of(
1216                vec![
1217                    field("NoPartyIDs", 453),
1218                    field("PartyID", 448),
1219                    field("NoPartySubIDs", 802),
1220                    field("PartySubID", 523),
1221                ],
1222                vec![
1223                    component(
1224                        "PtysSubGrp",
1225                        vec![group(802, false, vec![field_ref(523, false)])],
1226                    ),
1227                    component(
1228                        "Parties",
1229                        vec![group(
1230                            453,
1231                            false,
1232                            vec![field_ref(448, false), component_ref("PtysSubGrp", false)],
1233                        )],
1234                    ),
1235                ],
1236                vec![message(
1237                    "NewOrderSingle",
1238                    vec![component_ref("Parties", false)],
1239                )],
1240            );
1241
1242            let dictionary = spec.resolve().unwrap();
1243
1244            let parties = group_at(dictionary.messages().next().unwrap(), 0);
1245            let Some(Member::Group(sub_ids)) = parties.members().nth(1) else {
1246                panic!("expected a nested group");
1247            };
1248            assert_eq!(
1249                sub_ids.declared_in(),
1250                &MemberContext::Component("PtysSubGrp".to_owned())
1251            );
1252            assert_eq!(sub_ids.component(), Some("PtysSubGrp"));
1253        }
1254
1255        #[test]
1256        fn a_component_wrapping_a_component_does_not_claim_its_group() {
1257            let spec = spec_of(
1258                parties_fields(),
1259                vec![
1260                    component(
1261                        "Inner",
1262                        vec![group(453, false, vec![field_ref(448, false)])],
1263                    ),
1264                    component("Outer", vec![component_ref("Inner", false)]),
1265                ],
1266                vec![message(
1267                    "NewOrderSingle",
1268                    vec![component_ref("Outer", false)],
1269                )],
1270            );
1271
1272            let dictionary = spec.resolve().unwrap();
1273
1274            let group = group_at(dictionary.messages().next().unwrap(), 0);
1275            assert_eq!(group.component(), Some("Inner"));
1276        }
1277
1278        #[test]
1279        fn an_empty_group_is_an_error() {
1280            let spec = spec_of(
1281                parties_fields(),
1282                vec![],
1283                vec![message("NewOrderSingle", vec![group(453, false, vec![])])],
1284            );
1285
1286            assert_eq!(
1287                spec.resolve().unwrap_err(),
1288                Error::EmptyGroup {
1289                    context: nos_context().group("NoPartyIDs"),
1290                }
1291            );
1292        }
1293
1294        #[test]
1295        fn a_group_of_an_empty_component_is_an_error() {
1296            let spec = spec_of(
1297                parties_fields(),
1298                vec![component("Nothing", vec![])],
1299                vec![message(
1300                    "NewOrderSingle",
1301                    vec![group(453, false, vec![component_ref("Nothing", true)])],
1302                )],
1303            );
1304
1305            assert_eq!(
1306                spec.resolve().unwrap_err(),
1307                Error::EmptyGroup {
1308                    context: nos_context().group("NoPartyIDs"),
1309                }
1310            );
1311        }
1312
1313        #[test]
1314        fn an_unknown_count_tag_is_an_error() {
1315            let spec = spec_of(
1316                vec![field("PartyID", 448)],
1317                vec![],
1318                vec![message(
1319                    "NewOrderSingle",
1320                    vec![group(453, false, vec![field_ref(448, false)])],
1321                )],
1322            );
1323
1324            assert_eq!(
1325                spec.resolve().unwrap_err(),
1326                Error::UnknownField {
1327                    context: nos_context(),
1328                    tag: Tag(453),
1329                }
1330            );
1331        }
1332
1333        #[test]
1334        fn a_cycle_through_a_group_is_an_error() {
1335            let spec = spec_of(
1336                parties_fields(),
1337                vec![component(
1338                    "Parties",
1339                    vec![group(453, false, vec![component_ref("Parties", false)])],
1340                )],
1341                vec![],
1342            );
1343
1344            assert_eq!(
1345                spec.resolve().unwrap_err(),
1346                Error::CircularComponent {
1347                    component: "Parties".to_owned(),
1348                }
1349            );
1350        }
1351
1352        #[test]
1353        fn a_tag_in_a_scope_and_in_its_group_is_an_error() {
1354            let spec = spec_of(
1355                parties_fields(),
1356                vec![],
1357                vec![message(
1358                    "NewOrderSingle",
1359                    vec![
1360                        field_ref(448, false),
1361                        group(453, false, vec![field_ref(448, false)]),
1362                    ],
1363                )],
1364            );
1365
1366            assert_eq!(
1367                spec.resolve().unwrap_err(),
1368                Error::DuplicateField {
1369                    tag: Tag(448),
1370                    first: nos_context(),
1371                    second: nos_context().group("NoPartyIDs"),
1372                }
1373            );
1374        }
1375
1376        #[test]
1377        fn a_count_tag_also_used_as_a_field_is_an_error() {
1378            let spec = spec_of(
1379                parties_fields(),
1380                vec![],
1381                vec![message(
1382                    "NewOrderSingle",
1383                    vec![
1384                        field_ref(453, false),
1385                        group(453, false, vec![field_ref(448, false)]),
1386                    ],
1387                )],
1388            );
1389
1390            assert_eq!(
1391                spec.resolve().unwrap_err(),
1392                Error::DuplicateField {
1393                    tag: Tag(453),
1394                    first: nos_context(),
1395                    second: nos_context(),
1396                }
1397            );
1398        }
1399
1400        #[test]
1401        fn sibling_groups_sharing_a_tag_are_an_error() {
1402            let mut fields = parties_fields();
1403            fields.push(field("NoNestedPartyIDs", 539));
1404            let spec = spec_of(
1405                fields,
1406                vec![],
1407                vec![message(
1408                    "NewOrderSingle",
1409                    vec![
1410                        group(453, false, vec![field_ref(448, false)]),
1411                        group(539, false, vec![field_ref(448, false)]),
1412                    ],
1413                )],
1414            );
1415
1416            assert_eq!(
1417                spec.resolve().unwrap_err(),
1418                Error::DuplicateField {
1419                    tag: Tag(448),
1420                    first: nos_context().group("NoPartyIDs"),
1421                    second: nos_context().group("NoNestedPartyIDs"),
1422                }
1423            );
1424        }
1425
1426        #[test]
1427        fn a_duplicate_within_an_instance_names_the_instance() {
1428            let spec = spec_of(
1429                parties_fields(),
1430                vec![],
1431                vec![message(
1432                    "NewOrderSingle",
1433                    vec![group(
1434                        453,
1435                        false,
1436                        vec![field_ref(448, false), field_ref(448, false)],
1437                    )],
1438                )],
1439            );
1440
1441            assert_eq!(
1442                spec.resolve().unwrap_err(),
1443                Error::DuplicateField {
1444                    tag: Tag(448),
1445                    first: nos_context().group("NoPartyIDs"),
1446                    second: nos_context().group("NoPartyIDs"),
1447                }
1448            );
1449        }
1450    }
1451}