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