1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
use crate::*;

#[derive(Clone, Debug)]
pub struct Type {
    pub comment: Option<&'static str>,
    pub example: Option<Example>,
    pub metas: Metas,

    /// When we have an adjacently-tagged enum, this field contains name of the
    /// field that should represent that enum's tag.
    pub tag: Option<&'static str>,

    /// Whether this type is serializable or not (think
    /// `#[serde(skip_serializing)]`).
    pub serializable: bool,

    /// Whether this type is deserializable or not (think
    /// `#[serde(skip_deserializing)]`).
    pub deserializable: bool,

    // Keeping the kind last improves legibility of debug-printing
    pub kind: TypeKind,
}

impl From<TypeKind> for Type {
    fn from(kind: TypeKind) -> Self {
        Self {
            comment: None,
            example: None,
            metas: Metas::default(),
            tag: None,
            serializable: true,
            deserializable: true,
            kind,
        }
    }
}

impl From<Fields> for Type {
    fn from(fields: Fields) -> Self {
        let kind: TypeKind = fields.into();
        kind.into()
    }
}

impl Type {
    /// Recursively walks through the current type, and when an enum is found,
    /// all its variants are converted to equivalent structs.
    pub(crate) fn enum_to_structs(&self) -> Option<Vec<Self>> {
        match &self.kind {
            TypeKind::Enum {
                tag: Tag::Adjacent { tag, content },
                variants,
            } => Some(
                variants
                    .iter()
                    .map(|variant| {
                        self.to_owned()
                            .adjacent_variant_to_struct(variant, tag, content)
                    })
                    .collect(),
            ),
            TypeKind::Enum {
                tag: Tag::Internal { tag },
                variants,
            } => Some(
                variants
                    .iter()
                    .map(|variant| {
                        self.to_owned().internal_variant_to_struct(variant, tag)
                    })
                    .collect(),
            ),
            TypeKind::Enum {
                tag: Tag::External,
                variants,
            } => Some(
                variants
                    .iter()
                    .map(|variant| {
                        self.to_owned().external_variant_to_struct(variant)
                    })
                    .collect(),
            ),
            TypeKind::Enum {
                tag: Tag::None,
                variants,
            } => Some(
                variants
                    .iter()
                    .map(|variant| {
                        self.to_owned().untagged_variant_to_struct(variant)
                    })
                    .collect(),
            ),
            TypeKind::Array { ty, size } => {
                ty.enum_to_structs().map(|mut types| {
                    types
                        .drain(..)
                        .map(|ty| {
                            self.with_kind(TypeKind::Array {
                                ty: Box::new(ty),
                                size: size.to_owned(),
                            })
                        })
                        .collect()
                })
            }
            TypeKind::Map { key, value } => {
                value.enum_to_structs().map(|mut types| {
                    types
                        .drain(..)
                        .map(|ty| {
                            self.with_kind(TypeKind::Map {
                                key: key.to_owned(),
                                value: Box::new(ty),
                            })
                        })
                        .collect()
                })
            }
            TypeKind::Optional { ty } => {
                ty.enum_to_structs().map(|mut types| {
                    types
                        .drain(..)
                        .map(|ty| {
                            self.with_kind(TypeKind::Optional {
                                ty: Box::new(ty),
                            })
                        })
                        .collect()
                })
            }
            TypeKind::Struct {
                fields: Fields::Named { fields },
                ..
            } => fields.iter().enumerate().find_map(|(i, (name, f))| {
                f.ty.enum_to_structs().map(|mut types| {
                    types
                        .drain(..)
                        .map(|ty| {
                            self.to_owned().replace_named_field_of_struct(
                                (name, ty.into()),
                                i,
                            )
                        })
                        .collect()
                })
            }),
            TypeKind::Struct {
                fields: Fields::Unnamed { fields },
                ..
            } => fields.iter().enumerate().find_map(|(i, f)| {
                f.ty.enum_to_structs().map(|mut types| {
                    types
                        .drain(..)
                        .map(|ty| {
                            self.to_owned()
                                .replace_unnamed_field_of_struct(ty.into(), i)
                        })
                        .collect()
                })
            }),
            TypeKind::Tuple { fields } => {
                fields.iter().enumerate().find_map(|(i, ty)| {
                    ty.enum_to_structs().map(|mut types| {
                        types
                            .drain(..)
                            .map(|ty| {
                                self.to_owned().replace_field_of_tuple(ty, i)
                            })
                            .collect()
                    })
                })
            }
            _ => None,
        }
    }

    /// Converts an adjacently tagged variant of an enum to an equivalent struct.
    ///
    /// This is done by creating a struct with the `tag`, `content` fields.
    fn adjacent_variant_to_struct(
        mut self,
        variant: &Variant,
        tag: &'static str,
        content: &'static str,
    ) -> Self {
        let mut new_fields = Vec::new();
        let mut tag_type: Type = TypeKind::String.into();
        tag_type.example = Some(Example::Simple(variant.id));

        new_fields.push((tag, tag_type.into()));
        new_fields.push((content, variant.fields.clone().into()));

        self.kind = Fields::Named { fields: new_fields }.into();
        self
    }

    /// Converts an internally tagged variant of an enum to an equivalent struct.
    ///
    /// This is done by creating a struct with the `tag` field, and then
    /// appending the fields of the original variant to it.
    fn internal_variant_to_struct(
        mut self,
        variant: &Variant,
        tag: &'static str,
    ) -> Self {
        let mut new_fields = Vec::new();
        let mut tag_type: Type = TypeKind::String.into();
        tag_type.example = Some(Example::Simple(variant.id));
        new_fields.push((tag, tag_type.into()));

        match variant.fields.clone() {
            Fields::Named { mut fields } => new_fields.append(&mut fields),
            Fields::Unnamed { .. } => panic!(
                "Internally tagged unnamed variants are unsupported in TOML"
            ),
            Fields::Unit => {}
        };

        self.kind = Fields::Named { fields: new_fields }.into();
        self
    }

    /// Converts an externally tagged variant of an enum to an equivalent struct.
    ///
    /// This is done by creating a struct with just one field, whose name is the
    /// name of the variant and its type is another struct with the original
    /// fields of the variant.
    fn external_variant_to_struct(mut self, variant: &Variant) -> Self {
        let mut new_fields = Vec::new();
        let new_type: Type = variant.fields.clone().into();
        new_fields.push((variant.id, new_type.into()));

        self.kind = Fields::Named { fields: new_fields }.into();
        self
    }

    /// Converts an untagged variant of an enum to an equivalent struct.
    ///
    /// This is done by creating a struct that contains the fields of the
    /// original variant.
    fn untagged_variant_to_struct(mut self, variant: &Variant) -> Self {
        self.kind = variant.fields.clone().into();
        self
    }

    fn with_kind(&self, kind: TypeKind) -> Self {
        Self {
            comment: self.comment,
            example: self.example,
            metas: self.metas.clone(),
            tag: self.tag,
            serializable: self.serializable,
            deserializable: self.deserializable,
            kind,
        }
    }

    fn replace_named_field_of_struct(
        mut self,
        new_field: (&'static str, Field),
        i: usize,
    ) -> Self {
        if let TypeKind::Struct {
            fields: Fields::Named { fields },
            ..
        } = &mut self.kind
        {
            fields[i] = new_field;
        }
        self
    }

    fn replace_unnamed_field_of_struct(
        mut self,
        new_field: Field,
        i: usize,
    ) -> Self {
        if let TypeKind::Struct {
            fields: Fields::Unnamed { fields },
            ..
        } = &mut self.kind
        {
            fields[i] = new_field;
        }
        self
    }

    fn replace_field_of_tuple(mut self, new_field: Type, i: usize) -> Self {
        if let TypeKind::Tuple { fields } = &mut self.kind {
            fields[i] = new_field;
        }
        self
    }
}