1
//! Multiplicity for encoding netdoc elements, via ad-hoc deref specialisation.
2
//!
3
//! This module supports type-based handling of multiplicity,
4
//! of Items (within Documents) and Arguments (in Item keyword lines).
5
//!
6
//! It is **for use by macros**, rather than directly.
7
//!
8
//! See also `parse2::multiplicity` which is the corresponding module for parsing.
9
//!
10
//! # Explanation
11
//!
12
//! We use autoref specialisation to allow macros to dispatch to
13
//! trait impls for `Vec<T>`, `Option<T>` etc. as well as simply unadorned `T`.
14
//!
15
//! When methods on `MultiplicitySelector` are called, the compiler finds
16
//! the specific implementation for `MultiplicitySelector<Option<_>>` or `..Vec<_>`,
17
//! or, failing that, derefs and finds the blanket impl on `&MultiplicitySelector<T>`.
18
//!
19
//! For Objects, where only `T` and `Option<T>` are allowed,
20
//! we use `OptionalityMethods`.
21
//!
22
//! We implement traits on helper types `struct `[`MultiplicitySelector<Field>`],
23
//! [`DeterminedMultiplicitySelector`] and [`SingletonMultiplicitySelector`].
24
//!
25
//! The three selector types allow us to force the compiler to nail down the multiplicity,
26
//! during type inference, before considering whether the "each" type implements the
27
//! required trait.
28
//!
29
//! This is done by calling the `.selector()` method:
30
//! deref specialisation and inherent method vs trait method priority selects
31
//! the appropriate `.selector()` method, giving *another* selector,
32
//! so that the compiler only considers other selector's `MultiplicityMethods`,
33
//! when `.check_...` methods are used.
34
//! Otherwise, when a field has type (say) `Vec<NotItemValueParseable>`,
35
//! a call to `.check_item_value_encodable` could be resolved by autoref
36
//! so the compiler reports that **`Vec<..>`** doesn't implement the needed trait.
37
//! We prevent this by having
38
//! [`MultiplicitySelector::<Vec<_>>::default().selector()`](MultiplicitySelector::<Vec<T>>::selector)
39
//! be an inherent method returning [`DeterminedMultiplicitySelector`].
40
//!
41
//! `SingletonMultiplicitySelector` is used explicitly in the derive when we
42
//! know that we want to encode exactly one element:
43
//! for example, a document's intro item cannot be repeated or omitted.
44

            
45
use super::*;
46

            
47
/// Helper type that allows us to select an impl of `MultiplicityMethods`
48
///
49
/// **For use by macros**.
50
///
51
/// This is distinct from `parse2::MultiplicitySelector`,
52
/// principally because it has the opposite variance.
53
#[derive(Educe)]
54
#[educe(Clone, Copy, Default)]
55
pub struct MultiplicitySelector<Field>(PhantomData<fn(Field)>);
56

            
57
/// Helper type implementing `MultiplicityMethods`, after the multiplicity is determined
58
///
59
/// **For use by macros**.
60
#[derive(Educe)]
61
#[educe(Clone, Copy, Default)]
62
pub struct DeterminedMultiplicitySelector<Field>(PhantomData<fn(Field)>);
63

            
64
/// Helper type implementing `MultiplicityMethods`, when a field is statically a singleton
65
///
66
/// **For use by macros**.
67
#[derive(Educe)]
68
#[educe(Clone, Copy, Default)]
69
pub struct SingletonMultiplicitySelector<Field>(PhantomData<fn(Field)>);
70

            
71
/// Methods for handling some multiplicity of netdoc elements, during encoding
72
///
73
/// **For use by macros**.
74
///
75
/// Each multiplicity impl allows us to iterate over the element(s).
76
///
77
/// Methods are also provided for typechecking, which are used by the derive macro to
78
/// produce reasonable error messages when a trait impl is missing.
79
//
80
// When adding features here, for example by implementing this trait,
81
// update the documentation in the `NetdocEncodable` and `ItemValueEncodable` derives.
82
pub trait MultiplicityMethods<'f>: Copy + Sized {
83
    /// The value for each thing.
84
    type Each: Sized + 'f;
85

            
86
    /// The input type: the type of the field in the netdoc or item struct.
87
    type Field: Sized;
88

            
89
    /// Return the appropriate implementor of `MultiplicityMethods`
90
252
    fn selector(self) -> Self {
91
252
        self
92
252
    }
93

            
94
    /// Yield the items, in a stable order
95
    fn iter_ordered(self, f: &'f Self::Field) -> impl Iterator<Item = &'f Self::Each> + 'f;
96

            
97
    /// Cause a compiler error if the element is not `NetdocEncodable`
98
28
    fn check_netdoc_encodable(self)
99
28
    where
100
28
        Self::Each: NetdocEncodable,
101
    {
102
28
    }
103
    /// Cause a compiler error if the element is not `ItemValueEncodable`
104
102
    fn check_item_value_encodable(self)
105
102
    where
106
102
        Self::Each: ItemValueEncodable,
107
    {
108
102
    }
109
    /// Cause a compiler error if the element is not `ItemArgument`
110
52
    fn check_item_argument_encodable(self)
111
52
    where
112
52
        Self::Each: ItemArgument,
113
    {
114
52
    }
115
    /// Cause a compiler error if the element is not `ItemObjectEncodable`
116
6
    fn check_item_object_encodable(self)
117
6
    where
118
6
        Self::Each: ItemObjectEncodable,
119
    {
120
6
    }
121
}
122

            
123
impl<T> MultiplicitySelector<Vec<T>> {
124
    /// Return the appropriate implementor of `MultiplicityMethods`
125
    ///
126
    /// This is an inherent method so that it doesn't need the `EncodeOrd` bounds:
127
    /// that way if `EncodeOrd` is not implemented, we get a message about that,
128
    /// rather than a complaint that `ItemValueEncodable` isn't impl for `Vec<T>`.
129
44
    pub fn selector(self) -> DeterminedMultiplicitySelector<Vec<T>> {
130
44
        DeterminedMultiplicitySelector::default()
131
44
    }
132
}
133
impl<'f, T: EncodeOrd + 'f> MultiplicityMethods<'f> for DeterminedMultiplicitySelector<Vec<T>> {
134
    type Each = T;
135
    type Field = Vec<T>;
136
44
    fn iter_ordered(self, f: &'f Self::Field) -> impl Iterator<Item = &'f Self::Each> {
137
44
        let mut v = f.iter().collect_vec();
138
44
        v.sort_by(|a, b| a.encode_cmp(*b));
139
44
        v.into_iter()
140
44
    }
141
}
142
impl<'f, T: 'f> MultiplicityMethods<'f> for MultiplicitySelector<BTreeSet<T>> {
143
    type Each = T;
144
    type Field = BTreeSet<T>;
145
    fn iter_ordered(self, f: &'f Self::Field) -> impl Iterator<Item = &'f Self::Each> {
146
        f.iter()
147
    }
148
}
149
impl<'f, T: 'f> MultiplicityMethods<'f> for MultiplicitySelector<Option<T>> {
150
    type Each = T;
151
    type Field = Option<T>;
152
154
    fn iter_ordered(self, f: &'f Self::Field) -> impl Iterator<Item = &'f Self::Each> + 'f {
153
154
        f.iter()
154
154
    }
155
}
156
impl<'f, T: 'f> MultiplicityMethods<'f> for &'_ MultiplicitySelector<T> {
157
    type Each = T;
158
    type Field = T;
159
70
    fn iter_ordered(self, f: &'f Self::Field) -> impl Iterator<Item = &'f Self::Each> + 'f {
160
70
        iter::once(f)
161
70
    }
162
}
163
impl<'f, T: 'f> MultiplicityMethods<'f> for SingletonMultiplicitySelector<T> {
164
    type Each = T;
165
    type Field = T;
166
    fn iter_ordered(self, f: &'f Self::Field) -> impl Iterator<Item = &'f Self::Each> + 'f {
167
        iter::once(f)
168
    }
169
}
170

            
171
/// Methods for handling optionality of a netdoc Object, during encoding
172
///
173
// This could be used for things other than Object, if there were any thing
174
// that supported Option but not Vec.
175
//
176
/// **For use by macros**.
177
///
178
/// Each impl allows us to visit an optional element.
179
pub trait OptionalityMethods: Copy + Sized {
180
    /// The possibly-present element.
181
    type Each: Sized + 'static;
182

            
183
    /// The input type: the type of the field in the item struct.
184
    type Field: Sized;
185

            
186
    /// Yield the elemnet, if there is one
187
    fn as_option<'f>(self, f: &'f Self::Field) -> Option<&'f Self::Each>;
188
}
189
impl<T: 'static> OptionalityMethods for MultiplicitySelector<Option<T>> {
190
    type Each = T;
191
    type Field = Option<T>;
192
12
    fn as_option<'f>(self, f: &'f Self::Field) -> Option<&'f Self::Each> {
193
12
        f.as_ref()
194
12
    }
195
}
196
impl<T: 'static> OptionalityMethods for &'_ MultiplicitySelector<T> {
197
    type Each = T;
198
    type Field = T;
199
6
    fn as_option<'f>(self, f: &'f Self::Field) -> Option<&'f Self::Each> {
200
6
        Some(f)
201
6
    }
202
}