has_layout.rs 3.17 KB
Newer Older
Hero Bird's avatar
Hero Bird committed
1
2
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
//
3
4
5
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
Hero Bird's avatar
Hero Bird committed
6
//
7
//     http://www.apache.org/licenses/LICENSE-2.0
Hero Bird's avatar
Hero Bird committed
8
//
9
10
11
12
13
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Hero Bird's avatar
Hero Bird committed
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{
    self,
    parse::Result,
    parse_quote,
    punctuated::Punctuated,
    Data,
    DataStruct,
    DeriveInput,
    Field,
    Fields,
    Token,
};

Hero Bird's avatar
Hero Bird committed
30
31
use crate::impl_wrapper::wrap;

Hero Bird's avatar
Hero Bird committed
32
pub fn generate(input: TokenStream2) -> TokenStream2 {
Qinxuan Chen's avatar
Qinxuan Chen committed
33
34
35
    match generate_impl(input) {
        Ok(output) => output,
        Err(err) => err.to_compile_error(),
Hero Bird's avatar
Hero Bird committed
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
    }
}

pub fn generate_impl(input: TokenStream2) -> Result<TokenStream2> {
    let mut ast: DeriveInput = syn::parse2(input)?;

    ast.generics.type_params_mut().for_each(|p| {
        p.bounds.push(parse_quote!(_ink_abi::HasLayout));
    });

    let ident = &ast.ident;
    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();

    let layout = match &ast.data {
        Data::Struct(ref s) => generate_struct_layout(s),
        Data::Enum(ref _e) => bail!(&ast, "enums are not supported"),
        Data::Union(ref _u) => bail!(&ast, "unions are not supported"),
    };

    let has_layout_impl = quote! {
        impl #impl_generics _ink_abi::HasLayout for #ident #ty_generics #where_clause {
            fn layout(&self) -> _ink_abi::StorageLayout {
                #layout.into()
            }
        }
    };

63
    Ok(wrap(has_layout_impl))
Hero Bird's avatar
Hero Bird committed
64
65
66
67
68
69
70
71
72
73
74
75
}

fn generate_fields_layout<'a>(
    fields: &'a Punctuated<Field, Token![,]>,
) -> impl Iterator<Item = TokenStream2> + 'a {
    fields.iter().enumerate().map(|(n, field)| {
        let ident = &field.ident;
        if let Some(ident) = ident {
            quote! {
                _ink_abi::LayoutField::new(stringify!(#ident), self.#ident.layout())
            }
        } else {
76
            let n = proc_macro2::Literal::usize_unsuffixed(n);
Hero Bird's avatar
Hero Bird committed
77
78
79
80
81
82
83
84
85
86
            quote! {
                _ink_abi::LayoutField::new(stringify!(#n), self.#n.layout())
            }
        }
    })
}

fn generate_struct_fields_layout(fields: &Punctuated<Field, Token![,]>) -> TokenStream2 {
    let fields_layout = generate_fields_layout(fields);
    quote! {
Andrew Jones's avatar
Andrew Jones committed
87
        use scale_info::Metadata as _;
Hero Bird's avatar
Hero Bird committed
88
89
90
91
92
93
94
95
96
97
98
99
        _ink_abi::LayoutStruct::new(Self::meta_type(), __core::vec![
            #( #fields_layout, )*
        ])
    }
}

fn generate_struct_layout(data_struct: &DataStruct) -> TokenStream2 {
    match data_struct.fields {
        Fields::Named(ref fs) => generate_struct_fields_layout(&fs.named),
        Fields::Unnamed(ref fs) => generate_struct_fields_layout(&fs.unnamed),
        Fields::Unit => {
            quote! {
Andrew Jones's avatar
Andrew Jones committed
100
                _ink_abi::LayoutStruct::new(<Self as scale_info::Metadata>::meta_type(), Vec::new())
Hero Bird's avatar
Hero Bird committed
101
102
103
104
            }
        }
    }
}