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