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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
//
//   This Source Code Form is subject to the terms of the Mozilla Public
//   License, v. 2.0. If a copy of the MPL was not distributed with this
//   file, You can obtain one at http://mozilla.org/MPL/2.0/.
//
#![deny(missing_docs)]
#![doc = include_str!("../README.md")]

use std::{
    borrow::Cow,
    collections::{BTreeMap, BTreeSet, HashMap, HashSet},
};

use serde::{Deserialize, Serialize};

/// A derive macro that helps implementing [`AsTypeDescription`]
pub use type_description_derive::TypeDescription;

/// Rendering support for [`struct@TypeDescription`]s
#[cfg(any(feature = "render_markdown", feature = "render_terminal"))]
pub mod render;

/// Generic description of a type
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub struct TypeDescription {
    name: String,
    kind: TypeKind,
    doc: Option<Cow<'static, str>>,
}

impl TypeDescription {
    /// Construct a new generic type description
    #[must_use]
    pub fn new(name: String, kind: TypeKind, doc: Option<&'static str>) -> Self {
        Self {
            name,
            kind,
            doc: doc.map(Cow::Borrowed),
        }
    }

    /// Get a reference to the type's documentation.
    #[must_use]
    pub fn doc(&self) -> Option<&str> {
        self.doc.as_deref()
    }

    /// Get a reference to the type's kind.
    #[must_use]
    pub fn kind(&self) -> &TypeKind {
        &self.kind
    }

    /// Get the type's name.
    #[must_use]
    pub fn name(&self) -> &str {
        &self.name
    }
}

/// Representation of an enum
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub enum EnumVariantRepresentation {
    /// The enum is represented by a string
    ///
    /// This is the case with unit variants for example
    String(Cow<'static, str>),
    /// The enum is represented by the value presented here
    Wrapped(Box<TypeDescription>),
}

/// The kind of enum tagging used by the [`TypeKind::Enum`]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub enum TypeEnumKind {
    /// An internal tag with the given tag name
    Tagged(Cow<'static, str>),
    /// An untagged enum variant
    Untagged,
}

/// A field in a [`TypeKind::Struct`]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub struct StructField {
    name: Cow<'static, str>,
    doc: Option<Cow<'static, str>>,
    kind: TypeDescription,
    optional: bool,
}

impl StructField {
    /// Create a new [`StructField`]
    pub fn new(
        name: &'static str,
        doc: Option<&'static str>,
        kind: TypeDescription,
        optional: bool,
    ) -> Self {
        Self {
            name: Cow::Borrowed(name),
            doc: doc.map(Cow::Borrowed),
            kind,
            optional,
        }
    }

    /// Get the field's name.
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    /// Get the field's doc.
    pub fn doc(&self) -> Option<&str> {
        self.doc.as_deref()
    }

    /// Get the field's kind.
    pub fn kind(&self) -> &TypeDescription {
        &self.kind
    }

    /// Whether this field is optional
    pub fn optional(&self) -> bool {
        self.optional
    }
}

/// A variant in a [`TypeKind::Enum`]
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub struct EnumVariant {
    name: Cow<'static, str>,
    doc: Option<Cow<'static, str>>,
    repr: EnumVariantRepresentation,
}

impl EnumVariant {
    /// Create a new [`StructField`]
    pub fn new(
        name: &'static str,
        doc: Option<&'static str>,
        repr: EnumVariantRepresentation,
    ) -> Self {
        Self {
            name: Cow::Borrowed(name),
            doc: doc.map(Cow::Borrowed),
            repr,
        }
    }

    /// Get the variants's name.
    pub fn name(&self) -> &str {
        self.name.as_ref()
    }

    /// Get the variants's doc.
    pub fn doc(&self) -> Option<&str> {
        self.doc.as_deref()
    }

    /// Get the variants's representation.
    pub fn repr(&self) -> &EnumVariantRepresentation {
        &self.repr
    }
}

/// The specific kind a [`struct@TypeDescription`] represents
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub enum TypeKind {
    /// Type represents a boolean `true`/`false`
    Bool,

    /// Type represents an integer `1, 10, 200, 10_000, ...`
    Integer {
        /// Sign of the integer
        sign: Sign,

        /// Size of the integer
        size: u8,
    },

    /// Type represents a floating point value `1.0, 20.235, 3.1419`
    Float {
        /// The size of the value
        size: u8,
    },

    /// Type represents a string
    String,

    /// Wrap another type
    ///
    /// This is particularly useful if you want to restrict another kind. The common example is a
    /// `Port` type which is represented as a `u16` but with an explanation of what it is
    /// meant to represent.
    Wrapped(Box<TypeDescription>),

    /// Type represents an array of values of the given [`TypeKind`]
    Array(Box<TypeDescription>),

    /// Type represents a hashmap of named types of the same type
    HashMap {
        /// The key of the HashMap
        key: Box<TypeDescription>,
        /// The value of the HashMap
        value: Box<TypeDescription>,
    },

    /// Type represents a map of different types
    Struct(Vec<StructField>),

    /// Type represents multiple choice of type variants
    Enum(TypeEnumKind, Vec<EnumVariant>),
}

/// Whether an integer is a signed integer or an unsigned integer
#[derive(Debug, Serialize, Deserialize, PartialEq, Eq, Hash, Clone)]
pub enum Sign {
    /// A signed integer
    Signed,

    /// An unsigned integer
    Unsigned,
}

/// Turn a Rust type into a [`struct@TypeDescription`] object
///
/// Crate authors can either implement this manually or use the [`derive@TypeDescription`] derive
/// macro.
pub trait AsTypeDescription {
    /// Get a [`struct@TypeDescription`] object from the type
    fn as_type_description() -> TypeDescription;
}

impl<T: AsTypeDescription> AsTypeDescription for Option<T> {
    fn as_type_description() -> TypeDescription {
        TypeDescription::new(
            format!("An optional '{}'", T::as_type_description().name()),
            TypeKind::Wrapped(Box::new(T::as_type_description())),
            None,
        )
    }
}

impl<T: AsTypeDescription> AsTypeDescription for Vec<T> {
    fn as_type_description() -> TypeDescription {
        TypeDescription::new(
            format!("Array of '{}'s", T::as_type_description().name()),
            TypeKind::Array(Box::new(T::as_type_description())),
            None,
        )
    }
}

impl<K: AsTypeDescription, V: AsTypeDescription> AsTypeDescription for HashMap<K, V> {
    fn as_type_description() -> TypeDescription {
        TypeDescription::new(
            format!(
                "Table of '{} => {}'",
                K::as_type_description().name(),
                V::as_type_description().name()
            ),
            TypeKind::HashMap {
                key: Box::new(K::as_type_description()),
                value: Box::new(V::as_type_description()),
            },
            None,
        )
    }
}

impl<K: AsTypeDescription, V: AsTypeDescription> AsTypeDescription for BTreeMap<K, V> {
    fn as_type_description() -> TypeDescription {
        TypeDescription::new(
            format!(
                "Table of '{} => {}'",
                K::as_type_description().name(),
                V::as_type_description().name()
            ),
            TypeKind::HashMap {
                key: Box::new(K::as_type_description()),
                value: Box::new(V::as_type_description()),
            },
            None,
        )
    }
}

impl<T: AsTypeDescription> AsTypeDescription for HashSet<T> {
    fn as_type_description() -> TypeDescription {
        TypeDescription::new(
            format!("List of unique '{}'", T::as_type_description().name(),),
            TypeKind::Array(Box::new(T::as_type_description())),
            None,
        )
    }
}

impl<T: AsTypeDescription> AsTypeDescription for BTreeSet<T> {
    fn as_type_description() -> TypeDescription {
        TypeDescription::new(
            format!("List of unique '{}'", T::as_type_description().name(),),
            TypeKind::Array(Box::new(T::as_type_description())),
            None,
        )
    }
}

macro_rules! impl_config_kind {
    ($kind:expr; $name:expr; $doc:expr => $($typ:ty),+) => {
        $(
            impl AsTypeDescription for $typ {
                fn as_type_description() -> TypeDescription {
                    TypeDescription::new({$name}.into(), $kind, Some($doc))
                }
            }
        )+
    };
}

impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 64 }; "Integer"; "A signed integer with 64 bits" => i64);
impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 64 }; "Integer"; "A signed integer with 64 bits that cannot be zero" => std::num::NonZeroI64);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 64 }; "Integer"; "An unsigned integer with 64 bits" => u64);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 64 }; "Integer"; "An unsigned integer with 64 bits that cannot be zero" => std::num::NonZeroU64);

impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 32 }; "Integer"; "A signed integer with 32 bits" => i32);
impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 32 }; "Integer"; "A signed integer with 32 bits that cannot be zero" => std::num::NonZeroI32);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 32 }; "Integer"; "An unsigned integer with 32 bits" => u32);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 32 }; "Integer"; "An unsigned integer with 32 bits that cannot be zero" => std::num::NonZeroU32);

impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 16 }; "Integer"; "A signed integer with 16 bits" => i16);
impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 16 }; "Integer"; "A signed integer with 16 bits that cannot be zero" => std::num::NonZeroI16);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 16 }; "Integer"; "An unsigned integer with 16 bits" => u16);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 16 }; "Integer"; "An unsigned integer with 16 bits that cannot be zero" => std::num::NonZeroU16);

impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 8 }; "Integer"; "A signed integer with 8 bits" => i8);
impl_config_kind!(TypeKind::Integer { sign: Sign::Signed, size: 8 }; "Integer"; "A signed integer with 8 bits that cannot be zero" => std::num::NonZeroI8);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 8 }; "Integer"; "An unsigned integer with 8 bits" => u8);
impl_config_kind!(TypeKind::Integer { sign: Sign::Unsigned, size: 8 }; "Integer"; "An unsigned integer with 8 bits that cannot be zero" => std::num::NonZeroU8);

impl_config_kind!(TypeKind::Float { size: 64 }; "Float"; "A floating point value with 64 bits" => f64);
impl_config_kind!(TypeKind::Float { size: 32 }; "Float"; "A floating point value with 32 bits" => f32);

impl_config_kind!(TypeKind::Bool; "Boolean"; "A boolean" => bool);
impl_config_kind!(TypeKind::String; "String"; "An UTF-8 string" => String);

impl_config_kind!(TypeKind::String; "String"; "A socket address" => std::net::SocketAddr);
impl_config_kind!(TypeKind::String; "String"; "An IPv4 socket address" => std::net::SocketAddrV4);
impl_config_kind!(TypeKind::String; "String"; "An IPv6 socket address" => std::net::SocketAddrV6);

#[cfg(feature = "bytesize")]
impl_config_kind!(TypeKind::String; "String"; "A number of Bytes" => bytesize::ByteSize);

#[cfg(feature = "url")]
impl_config_kind!(TypeKind::String; "String"; "An URL" => url::Url);

#[cfg(feature = "uuid")]
impl_config_kind!(TypeKind::String; "String"; "A UUID" => uuid::Uuid);

impl_config_kind!(TypeKind::String; "String"; "A filesystem path" => std::path::PathBuf);

#[cfg(test)]
mod tests {
    use std::collections::HashMap;

    use super::{AsTypeDescription, Sign, TypeDescription, TypeKind};

    #[test]
    fn verify_correct_config_kinds() {
        assert!(matches!(
            Vec::<f64>::as_type_description(),
            TypeDescription {
                doc: None,
                kind: TypeKind::Array(x),
                ..
            } if matches!(x.kind(), TypeKind::Float { size: 64 })
        ));

        let complex_config = HashMap::<String, Vec<HashMap<String, String>>>::as_type_description();
        println!("Complex config: {:#?}", complex_config);

        assert!(
            matches!(complex_config.kind(), TypeKind::HashMap { value, .. } if matches!(value.kind(), TypeKind::Array(arr) if matches!(arr.kind(), TypeKind::HashMap { value, .. } if matches!(value.kind(), TypeKind::String))))
        );
    }

    #[test]
    fn test_key_value() {
        let kv = HashMap::<i32, Vec<f64>>::as_type_description();

        match kv.kind() {
            TypeKind::HashMap { key, value } => {
                match value.kind() {
                    TypeKind::Array(arr) => {
                        match arr.kind() {
                            TypeKind::Float { size: 64 } => { /* good */ }
                            other => panic!("Expected Float, got {:?}", other),
                        }
                    }

                    other => panic!("Expected Array, got {:?}", other),
                }

                match key.kind() {
                    TypeKind::Integer {
                        size: 32,
                        sign: Sign::Signed,
                    } => { /* good */ }
                    other => panic!("Expected Integer, got {:?}", other),
                }
            }

            other => panic!("Expected HashMap, got {:?}", other),
        }
    }
}