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
// Copyright 2019-2022 Parity Technologies (UK) Ltd.
// This file is dual-licensed as Apache-2.0 or GPL-3.0.
// see LICENSE for license details.

mod composite_def;
mod derives;
#[cfg(test)]
mod tests;
mod type_def;
mod type_def_params;
mod type_path;

use proc_macro2::{
    Ident,
    Span,
    TokenStream,
};
use proc_macro_error::abort_call_site;
use quote::{
    quote,
    ToTokens,
};
use scale_info::{
    form::PortableForm,
    PortableRegistry,
    Type,
    TypeDef,
};
use std::collections::{
    BTreeMap,
    HashMap,
};

pub use self::{
    composite_def::{
        CompositeDef,
        CompositeDefFieldType,
        CompositeDefFields,
    },
    derives::{
        Derives,
        DerivesRegistry,
    },
    type_def::TypeDefGen,
    type_def_params::TypeDefParameters,
    type_path::{
        TypeParameter,
        TypePath,
        TypePathType,
    },
};

pub type Field = scale_info::Field<PortableForm>;

/// Generate a Rust module containing all types defined in the supplied [`PortableRegistry`].
#[derive(Debug)]
pub struct TypeGenerator<'a> {
    /// The name of the module which will contain the generated types.
    types_mod_ident: Ident,
    /// Registry of type definitions to be transformed into Rust type definitions.
    type_registry: &'a PortableRegistry,
    /// User defined overrides for generated types.
    type_substitutes: HashMap<String, syn::TypePath>,
    /// Set of derives with which to annotate generated types.
    derives: DerivesRegistry,
}

impl<'a> TypeGenerator<'a> {
    /// Construct a new [`TypeGenerator`].
    pub fn new(
        type_registry: &'a PortableRegistry,
        root_mod: &'static str,
        type_substitutes: HashMap<String, syn::TypePath>,
        derives: DerivesRegistry,
    ) -> Self {
        let root_mod_ident = Ident::new(root_mod, Span::call_site());
        Self {
            types_mod_ident: root_mod_ident,
            type_registry,
            type_substitutes,
            derives,
        }
    }

    /// Generate a module containing all types defined in the supplied type registry.
    pub fn generate_types_mod(&self) -> Module {
        let mut root_mod =
            Module::new(self.types_mod_ident.clone(), self.types_mod_ident.clone());

        for (id, ty) in self.type_registry.types().iter().enumerate() {
            if ty.ty().path().namespace().is_empty() {
                // prelude types e.g. Option/Result have no namespace, so we don't generate them
                continue
            }
            self.insert_type(
                ty.ty().clone(),
                id as u32,
                ty.ty().path().namespace().to_vec(),
                &self.types_mod_ident,
                &mut root_mod,
            )
        }

        root_mod
    }

    fn insert_type(
        &'a self,
        ty: Type<PortableForm>,
        id: u32,
        path: Vec<String>,
        root_mod_ident: &Ident,
        module: &mut Module,
    ) {
        let joined_path = path.join("::");
        if self.type_substitutes.contains_key(&joined_path) {
            return
        }

        let segment = path.first().expect("path has at least one segment");
        let mod_ident = Ident::new(segment, Span::call_site());

        let child_mod = module
            .children
            .entry(mod_ident.clone())
            .or_insert_with(|| Module::new(mod_ident, root_mod_ident.clone()));

        if path.len() == 1 {
            child_mod
                .types
                .insert(ty.path().clone(), TypeDefGen::from_type(ty, self));
        } else {
            self.insert_type(ty, id, path[1..].to_vec(), root_mod_ident, child_mod)
        }
    }

    /// # Panics
    ///
    /// If no type with the given id found in the type registry.
    pub fn resolve_type(&self, id: u32) -> Type<PortableForm> {
        self.type_registry
            .resolve(id)
            .unwrap_or_else(|| panic!("No type with id {} found", id))
            .clone()
    }

    /// Get the type path for a field of a struct or an enum variant, providing any generic
    /// type parameters from the containing type. This is for identifying where a generic type
    /// parameter is used in a field type e.g.
    ///
    /// ```rust
    /// struct S<T> {
    ///     a: T, // `T` is the "parent" type param from the containing type.
    ///     b: Vec<Option<T>>, // nested use of generic type param `T`.
    /// }
    /// ```
    ///
    /// This allows generating the correct generic field type paths.
    ///
    /// # Panics
    ///
    /// If no type with the given id found in the type registry.
    pub fn resolve_field_type_path(
        &self,
        id: u32,
        parent_type_params: &[TypeParameter],
    ) -> TypePath {
        self.resolve_type_path_recurse(id, true, parent_type_params)
    }

    /// Get the type path for the given type identifier.
    ///
    /// # Panics
    ///
    /// If no type with the given id found in the type registry.
    pub fn resolve_type_path(&self, id: u32) -> TypePath {
        self.resolve_type_path_recurse(id, false, &[])
    }

    /// Visit each node in a possibly nested type definition to produce a type path.
    ///
    /// e.g `Result<GenericStruct<NestedGenericStruct<T>>, String>`
    fn resolve_type_path_recurse(
        &self,
        id: u32,
        is_field: bool,
        parent_type_params: &[TypeParameter],
    ) -> TypePath {
        if let Some(parent_type_param) = parent_type_params
            .iter()
            .find(|tp| tp.concrete_type_id == id)
        {
            return TypePath::Parameter(parent_type_param.clone())
        }

        let mut ty = self.resolve_type(id);

        if ty.path().ident() == Some("Cow".to_string()) {
            ty = self.resolve_type(
                ty.type_params()[0]
                    .ty()
                    .expect("type parameters to Cow are not expected to be skipped; qed")
                    .id(),
            )
        }

        let params = ty
            .type_params()
            .iter()
            .filter_map(|f| {
                f.ty().map(|f| {
                    self.resolve_type_path_recurse(f.id(), false, parent_type_params)
                })
            })
            .collect();

        let ty = match ty.type_def() {
            TypeDef::Composite(_) | TypeDef::Variant(_) => {
                let joined_path = ty.path().segments().join("::");
                if let Some(substitute_type_path) =
                    self.type_substitutes.get(&joined_path)
                {
                    TypePathType::Path {
                        path: substitute_type_path.clone(),
                        params,
                    }
                } else {
                    TypePathType::from_type_def_path(
                        ty.path(),
                        self.types_mod_ident.clone(),
                        params,
                    )
                }
            }
            TypeDef::Primitive(primitive) => {
                TypePathType::Primitive {
                    def: primitive.clone(),
                }
            }
            TypeDef::Array(arr) => {
                TypePathType::Array {
                    len: arr.len() as usize,
                    of: Box::new(self.resolve_type_path_recurse(
                        arr.type_param().id(),
                        false,
                        parent_type_params,
                    )),
                }
            }
            TypeDef::Sequence(seq) => {
                TypePathType::Vec {
                    of: Box::new(self.resolve_type_path_recurse(
                        seq.type_param().id(),
                        false,
                        parent_type_params,
                    )),
                }
            }
            TypeDef::Tuple(tuple) => {
                TypePathType::Tuple {
                    elements: tuple
                        .fields()
                        .iter()
                        .map(|f| {
                            self.resolve_type_path_recurse(
                                f.id(),
                                false,
                                parent_type_params,
                            )
                        })
                        .collect(),
                }
            }
            TypeDef::Compact(compact) => {
                TypePathType::Compact {
                    inner: Box::new(self.resolve_type_path_recurse(
                        compact.type_param().id(),
                        false,
                        parent_type_params,
                    )),
                    is_field,
                }
            }
            TypeDef::BitSequence(bitseq) => {
                TypePathType::BitVec {
                    bit_order_type: Box::new(self.resolve_type_path_recurse(
                        bitseq.bit_order_type().id(),
                        false,
                        parent_type_params,
                    )),
                    bit_store_type: Box::new(self.resolve_type_path_recurse(
                        bitseq.bit_store_type().id(),
                        false,
                        parent_type_params,
                    )),
                }
            }
        };

        TypePath::Type(ty)
    }

    /// Returns the derives to be applied to all generated types.
    pub fn default_derives(&self) -> &Derives {
        self.derives.default_derives()
    }

    /// Returns the derives to be applied to a generated type.
    pub fn type_derives(&self, ty: &Type<PortableForm>) -> Derives {
        let joined_path = ty.path().segments().join("::");
        let ty_path: syn::TypePath = syn::parse_str(&joined_path).unwrap_or_else(|e| {
            abort_call_site!("'{}' is an invalid type path: {:?}", joined_path, e,)
        });
        self.derives.resolve(&ty_path)
    }
}

/// Represents a Rust `mod`, containing generated types and child `mod`s.
#[derive(Debug)]
pub struct Module {
    name: Ident,
    root_mod: Ident,
    children: BTreeMap<Ident, Module>,
    types: BTreeMap<scale_info::Path<PortableForm>, TypeDefGen>,
}

impl ToTokens for Module {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let name = &self.name;
        let root_mod = &self.root_mod;
        let modules = self.children.values();
        let types = self.types.values().clone();

        tokens.extend(quote! {
            pub mod #name {
                use super::#root_mod;

                #( #modules )*
                #( #types )*
            }
        })
    }
}

impl Module {
    /// Create a new [`Module`], with a reference to the root `mod` for resolving type paths.
    pub(crate) fn new(name: Ident, root_mod: Ident) -> Self {
        Self {
            name,
            root_mod,
            children: BTreeMap::new(),
            types: BTreeMap::new(),
        }
    }

    /// Returns the module ident.
    pub fn ident(&self) -> &Ident {
        &self.name
    }
}