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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Since Borsh is not a self-descriptive format we have a way to describe types serialized with Borsh so that
//! we can deserialize serialized blobs without having Rust types available. Additionally, this can be used to
//! serialize content provided in a different format, e.g. JSON object `{"user": "alice", "message": "Message"}`
//! can be serialized by JS code into Borsh format such that it can be deserialized into `struct UserMessage {user: String, message: String}`
//! on Rust side.
//!
//! The important components are: `BorshSchema` trait, `Definition` and `Declaration` types, and `BorshSchemaContainer` struct.
//! * `BorshSchema` trait allows any type that implements it to be self-descriptive, i.e. generate it's own schema;
//! * `Declaration` is used to describe the type identifier, e.g. `HashMap<u64, String>`;
//! * `Definition` is used to describe the structure of the type;
//! * `BorshSchemaContainer` is used to store all declarations and defintions that are needed to work with a single type.

#![allow(dead_code)] // Unclear why rust check complains on fields of `Definition` variants.
use crate as borsh; // For `#[derive(BorshSerialize, BorshDeserialize)]`.
use crate::maybestd::{
    boxed::Box,
    collections::{hash_map::Entry, HashMap},
    format,
    string::{String, ToString},
    vec,
    vec::Vec,
};
use crate::{BorshDeserialize, BorshSchema as BorshSchemaMacro, BorshSerialize};

/// The type that we use to represent the declaration of the Borsh type.
pub type Declaration = String;
/// The type that we use for the name of the variant.
pub type VariantName = String;
/// The name of the field in the struct (can be used to convert JSON to Borsh using the schema).
pub type FieldName = String;
/// The type that we use to represent the definition of the Borsh type.
#[derive(PartialEq, Debug, BorshSerialize, BorshDeserialize, BorshSchemaMacro)]
pub enum Definition {
    /// A fixed-size array with the length known at the compile time and the same-type elements.
    Array { length: u32, elements: Declaration },
    /// A sequence of elements of length known at the run time and the same-type elements.
    Sequence { elements: Declaration },
    /// A fixed-size tuple with the length known at the compile time and the elements of different
    /// types.
    Tuple { elements: Vec<Declaration> },
    /// A tagged union, a.k.a enum. Tagged-unions have variants with associated structures.
    Enum {
        variants: Vec<(VariantName, Declaration)>,
    },
    /// A structure, structurally similar to a tuple.
    Struct { fields: Fields },
}

/// The collection representing the fields of a struct.
#[derive(PartialEq, Debug, BorshSerialize, BorshDeserialize, BorshSchemaMacro)]
pub enum Fields {
    /// The struct with named fields.
    NamedFields(Vec<(FieldName, Declaration)>),
    /// The struct with unnamed fields, structurally identical to a tuple.
    UnnamedFields(Vec<Declaration>),
    /// The struct with no fields.
    Empty,
}

/// All schema information needed to deserialize a single type.
#[derive(PartialEq, Debug, BorshSerialize, BorshDeserialize, BorshSchemaMacro)]
pub struct BorshSchemaContainer {
    /// Declaration of the type.
    pub declaration: Declaration,
    /// All definitions needed to deserialize the given type.
    pub definitions: HashMap<Declaration, Definition>,
}

/// The declaration and the definition of the type that can be used to (de)serialize Borsh without
/// the Rust type that produced it.
pub trait BorshSchema {
    /// Recursively, using DFS, add type definitions required for this type. For primitive types
    /// this is an empty map. Type definition explains how to serialize/deserialize a type.
    fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>);

    /// Helper method to add a single type definition to the map.
    fn add_definition(
        declaration: Declaration,
        definition: Definition,
        definitions: &mut HashMap<Declaration, Definition>,
    ) {
        match definitions.entry(declaration) {
            Entry::Occupied(occ) => {
                let existing_def = occ.get();
                assert_eq!(existing_def, &definition, "Redefining type schema for the same type name. Types with the same names are not supported.");
            }
            Entry::Vacant(vac) => {
                vac.insert(definition);
            }
        }
    }
    /// Get the name of the type without brackets.
    fn declaration() -> Declaration;

    fn schema_container() -> BorshSchemaContainer {
        let mut definitions = HashMap::new();
        Self::add_definitions_recursively(&mut definitions);
        BorshSchemaContainer {
            declaration: Self::declaration(),
            definitions,
        }
    }
}

impl<T> BorshSchema for Box<T>
where
    T: BorshSchema,
{
    fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
        T::add_definitions_recursively(definitions);
    }

    fn declaration() -> Declaration {
        T::declaration()
    }
}

impl BorshSchema for () {
    fn add_definitions_recursively(_definitions: &mut HashMap<Declaration, Definition>) {}

    fn declaration() -> Declaration {
        "nil".to_string()
    }
}

macro_rules! impl_for_renamed_primitives {
    ($($type: ident : $name: ident)+) => {
    $(
        impl BorshSchema for $type {
            fn add_definitions_recursively(_definitions: &mut HashMap<Declaration, Definition>) {}
            fn declaration() -> Declaration {
                stringify!($name).to_string()
            }
        }
    )+
    };
}

macro_rules! impl_for_primitives {
    ($($type: ident)+) => {
    impl_for_renamed_primitives!{$($type : $type)+}
    };
}

impl_for_primitives!(bool char f32 f64 i8 i16 i32 i64 i128 u8 u16 u32 u64 u128);
impl_for_renamed_primitives!(String: string);

macro_rules! impl_arrays {
    ($($len:expr)+) => {
    $(
    impl<T> BorshSchema for [T; $len]
    where
        T: BorshSchema,
    {
        fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
            let definition = Definition::Array { length: $len, elements: T::declaration() };
            Self::add_definition(Self::declaration(), definition, definitions);
            T::add_definitions_recursively(definitions);
        }
        fn declaration() -> Declaration {
            format!(r#"Array<{}, {}>"#, T::declaration(), $len)
        }
    }
    )+
    };
}

impl_arrays!(0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 32 64 65);

impl<T> BorshSchema for Option<T>
where
    T: BorshSchema,
{
    fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
        let definition = Definition::Enum {
            variants: vec![
                ("None".to_string(), <()>::declaration()),
                ("Some".to_string(), T::declaration()),
            ],
        };
        Self::add_definition(Self::declaration(), definition, definitions);
        T::add_definitions_recursively(definitions);
    }

    fn declaration() -> Declaration {
        format!(r#"Option<{}>"#, T::declaration())
    }
}

impl<T, E> BorshSchema for core::result::Result<T, E>
where
    T: BorshSchema,
    E: BorshSchema,
{
    fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
        let definition = Definition::Enum {
            variants: vec![
                ("Ok".to_string(), T::declaration()),
                ("Err".to_string(), E::declaration()),
            ],
        };
        Self::add_definition(Self::declaration(), definition, definitions);
        T::add_definitions_recursively(definitions);
    }

    fn declaration() -> Declaration {
        format!(r#"Result<{}, {}>"#, T::declaration(), E::declaration())
    }
}

impl<T> BorshSchema for Vec<T>
where
    T: BorshSchema,
{
    fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
        let definition = Definition::Sequence {
            elements: T::declaration(),
        };
        Self::add_definition(Self::declaration(), definition, definitions);
        T::add_definitions_recursively(definitions);
    }

    fn declaration() -> Declaration {
        format!(r#"Vec<{}>"#, T::declaration())
    }
}

impl<K, V> BorshSchema for HashMap<K, V>
where
    K: BorshSchema,
    V: BorshSchema,
{
    fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
        let definition = Definition::Sequence {
            elements: <(K, V)>::declaration(),
        };
        Self::add_definition(Self::declaration(), definition, definitions);
        <(K, V)>::add_definitions_recursively(definitions);
    }

    fn declaration() -> Declaration {
        format!(r#"HashMap<{}, {}>"#, K::declaration(), V::declaration())
    }
}

macro_rules! impl_tuple {
    ($($name:ident),+) => {
    impl<$($name),+> BorshSchema for ($($name),+)
    where
        $($name: BorshSchema),+
    {
        fn add_definitions_recursively(definitions: &mut HashMap<Declaration, Definition>) {
            let mut elements = vec![];
            $(
                elements.push($name::declaration());
            )+

            let definition = Definition::Tuple { elements };
            Self::add_definition(Self::declaration(), definition, definitions);
            $(
                $name::add_definitions_recursively(definitions);
            )+
        }

        fn declaration() -> Declaration {
            let params = vec![$($name::declaration()),+];
            format!(r#"Tuple<{}>"#, params.join(", "))
        }
    }
    };
}

impl_tuple!(T0, T1);
impl_tuple!(T0, T1, T2);
impl_tuple!(T0, T1, T2, T3);
impl_tuple!(T0, T1, T2, T3, T4);
impl_tuple!(T0, T1, T2, T3, T4, T5);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17);
impl_tuple!(T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18);
impl_tuple!(
    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19
);
impl_tuple!(
    T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, T17, T18, T19, T20
);

#[cfg(test)]
mod tests {
    use super::*;
    use crate::maybestd::collections::HashMap;

    macro_rules! map(
    () => { HashMap::new() };
    { $($key:expr => $value:expr),+ } => {
        {
            let mut m = HashMap::new();
            $(
                m.insert($key.to_string(), $value);
            )+
            m
        }
     };
    );

    #[test]
    fn simple_option() {
        let actual_name = Option::<u64>::declaration();
        let mut actual_defs = map!();
        Option::<u64>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Option<u64>", actual_name);
        assert_eq!(
            map! {"Option<u64>" =>
            Definition::Enum{ variants: vec![
                ("None".to_string(), "nil".to_string()),
                ("Some".to_string(), "u64".to_string()),
            ]}
            },
            actual_defs
        );
    }

    #[test]
    fn nested_option() {
        let actual_name = Option::<Option<u64>>::declaration();
        let mut actual_defs = map!();
        Option::<Option<u64>>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Option<Option<u64>>", actual_name);
        assert_eq!(
            map! {
            "Option<u64>" =>
                Definition::Enum {variants: vec![
                ("None".to_string(), "nil".to_string()),
                ("Some".to_string(), "u64".to_string()),
                ]},
            "Option<Option<u64>>" =>
                Definition::Enum {variants: vec![
                ("None".to_string(), "nil".to_string()),
                ("Some".to_string(), "Option<u64>".to_string()),
                ]}
            },
            actual_defs
        );
    }

    #[test]
    fn simple_vec() {
        let actual_name = Vec::<u64>::declaration();
        let mut actual_defs = map!();
        Vec::<u64>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Vec<u64>", actual_name);
        assert_eq!(
            map! {
            "Vec<u64>" => Definition::Sequence { elements: "u64".to_string() }
            },
            actual_defs
        );
    }

    #[test]
    fn nested_vec() {
        let actual_name = Vec::<Vec<u64>>::declaration();
        let mut actual_defs = map!();
        Vec::<Vec<u64>>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Vec<Vec<u64>>", actual_name);
        assert_eq!(
            map! {
            "Vec<u64>" => Definition::Sequence { elements: "u64".to_string() },
            "Vec<Vec<u64>>" => Definition::Sequence { elements: "Vec<u64>".to_string() }
            },
            actual_defs
        );
    }

    #[test]
    fn simple_tuple() {
        let actual_name = <(u64, String)>::declaration();
        let mut actual_defs = map!();
        <(u64, String)>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Tuple<u64, string>", actual_name);
        assert_eq!(
            map! {
                "Tuple<u64, string>" => Definition::Tuple { elements: vec![ "u64".to_string(), "string".to_string()]}
            },
            actual_defs
        );
    }

    #[test]
    fn nested_tuple() {
        let actual_name = <(u64, (u8, bool), String)>::declaration();
        let mut actual_defs = map!();
        <(u64, (u8, bool), String)>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Tuple<u64, Tuple<u8, bool>, string>", actual_name);
        assert_eq!(
            map! {
                "Tuple<u64, Tuple<u8, bool>, string>" => Definition::Tuple { elements: vec![
                    "u64".to_string(),
                    "Tuple<u8, bool>".to_string(),
                    "string".to_string(),
                ]},
                "Tuple<u8, bool>" => Definition::Tuple { elements: vec![ "u8".to_string(), "bool".to_string()]}
            },
            actual_defs
        );
    }

    #[test]
    fn simple_map() {
        let actual_name = HashMap::<u64, String>::declaration();
        let mut actual_defs = map!();
        HashMap::<u64, String>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("HashMap<u64, string>", actual_name);
        assert_eq!(
            map! {
                "HashMap<u64, string>" => Definition::Sequence { elements: "Tuple<u64, string>".to_string()} ,
                "Tuple<u64, string>" => Definition::Tuple { elements: vec![ "u64".to_string(), "string".to_string()]}
            },
            actual_defs
        );
    }

    #[test]
    fn simple_array() {
        let actual_name = <[u64; 32]>::declaration();
        let mut actual_defs = map!();
        <[u64; 32]>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Array<u64, 32>", actual_name);
        assert_eq!(
            map! {"Array<u64, 32>" => Definition::Array { length: 32, elements: "u64".to_string()}},
            actual_defs
        );
    }

    #[test]
    fn nested_array() {
        let actual_name = <[[[u64; 9]; 10]; 32]>::declaration();
        let mut actual_defs = map!();
        <[[[u64; 9]; 10]; 32]>::add_definitions_recursively(&mut actual_defs);
        assert_eq!("Array<Array<Array<u64, 9>, 10>, 32>", actual_name);
        assert_eq!(
            map! {
            "Array<u64, 9>" =>
                Definition::Array { length: 9, elements: "u64".to_string() },
            "Array<Array<u64, 9>, 10>" =>
                Definition::Array { length: 10, elements: "Array<u64, 9>".to_string() },
            "Array<Array<Array<u64, 9>, 10>, 32>" =>
                Definition::Array { length: 32, elements: "Array<Array<u64, 9>, 10>".to_string() }
            },
            actual_defs
        );
    }
}