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