spread_layout.rs 7.33 KB
Newer Older
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
// Copyright 2018-2020 Parity Technologies (UK) Ltd.
//
// 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
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// 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.

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;

/// Generates the tokens to compute the maximum of the numbers given via
/// their token streams at compilation time.
///
/// # Note
///
/// Since Rust currently does not allow conditionals in const contexts
/// we use the array indexing trick to compute the maximum element:
///
/// ```no_compile
/// max(a, b) = [a, b][(a < b) as usize]
/// ```
fn max_n(args: &[TokenStream2]) -> TokenStream2 {
    match args.split_first() {
        Some((head, rest)) => {
            let rest = max_n(rest);
            quote! {
                [#head, #rest][(#head < #rest) as usize]
            }
        }
        None => quote! { 0u64 },
    }
}

/// Generates the tokens for the `SpreadLayout` footprint of some type.
fn footprint(s: &synstructure::Structure) -> TokenStream2 {
    let variant_footprints = s
        .variants()
        .iter()
        .map(|variant| {
            variant
                .ast()
                .fields
                .iter()
                .map(|field| &field.ty)
52
                .map(|ty| quote! { <#ty as ::ink_core::storage::traits::SpreadLayout>::FOOTPRINT })
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
                .fold(quote! { 0u64 }, |lhs, rhs| {
                    quote! { (#lhs + #rhs) }
                })
        })
        .collect::<Vec<_>>();
    max_n(&variant_footprints[..])
}

/// Generates the tokens for the `SpreadLayout` `REQUIRES_DEEP_CLEAN_UP` constant for the given structure.
fn requires_deep_clean_up(s: &synstructure::Structure) -> TokenStream2 {
    s.variants()
        .iter()
        .map(|variant| {
            variant
            .ast()
            .fields
            .iter()
            .map(|field| &field.ty)
71
            .map(|ty| quote! { <#ty as ::ink_core::storage::traits::SpreadLayout>::REQUIRES_DEEP_CLEAN_UP })
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
            .fold(quote! { false }, |lhs, rhs| {
                quote! { (#lhs || #rhs) }
            })
        })
        .fold(quote! { false }, |lhs, rhs| {
            quote! { (#lhs || #rhs) }
        })
}

/// `SpreadLayout` derive implementation for `struct` types.
fn spread_layout_struct_derive(s: &synstructure::Structure) -> TokenStream2 {
    assert!(s.variants().len() == 1, "can only operate on structs");
    let footprint_body = footprint(s);
    let requires_deep_clean_up_body = requires_deep_clean_up(s);
    let variant: &synstructure::VariantInfo = &s.variants()[0];
    let pull_body = variant.construct(|field, _index| {
        let ty = &field.ty;
        quote! {
90
            <#ty as ::ink_core::storage::traits::SpreadLayout>::pull_spread(__key_ptr)
91
92
93
94
        }
    });
    let push_body = variant.each(|binding| {
        quote! {
95
            ::ink_core::storage::traits::SpreadLayout::push_spread(#binding, __key_ptr);
96
97
98
99
        }
    });
    let clear_body = s.each(|field| {
        quote! {
100
            ::ink_core::storage::traits::SpreadLayout::clear_spread(#field, __key_ptr);
101
102
103
        }
    });
    s.gen_impl(quote! {
104
        gen impl ::ink_core::storage::traits::SpreadLayout for @Self {
105
106
107
108
            #[allow(unused_comparisons)]
            const FOOTPRINT: u64 = #footprint_body;
            const REQUIRES_DEEP_CLEAN_UP: bool = #requires_deep_clean_up_body;

109
            fn pull_spread(__key_ptr: &mut ::ink_core::storage::traits::KeyPtr) -> Self {
110
111
                #pull_body
            }
112
            fn push_spread(&self, __key_ptr: &mut ::ink_core::storage::traits::KeyPtr) {
113
114
                match self { #push_body }
            }
115
            fn clear_spread(&self, __key_ptr: &mut ::ink_core::storage::traits::KeyPtr) {
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
                match self { #clear_body }
            }
        }
    })
}

/// `SpreadLayout` derive implementation for `enum` types.
fn spread_layout_enum_derive(s: &synstructure::Structure) -> TokenStream2 {
    assert!(s.variants().len() >= 2, "can only operate on enums");
    let footprint_body = footprint(s);
    let requires_deep_clean_up_body = requires_deep_clean_up(s);
    let pull_body = s
        .variants()
        .iter()
        .map(|variant| {
            variant.construct(|field, _index| {
                let ty = &field.ty;
                quote! {
134
                    <#ty as ::ink_core::storage::traits::SpreadLayout>::pull_spread(__key_ptr)
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
                }
            })
        })
        .enumerate()
        .fold(quote! {}, |acc, (index, variant)| {
            let index = index as u8;
            quote! {
                #acc
                #index => #variant,
            }
        });

    let push_body = s.variants().iter().enumerate().map(|(index, variant)| {
        let pat = variant.pat();
        let index = index as u8;
        let fields = variant.bindings().iter().map(|field| {
            quote! {
152
                ::ink_core::storage::traits::SpreadLayout::push_spread(#field, __key_ptr);
153
154
155
156
            }
        });
        quote! {
            #pat => {
157
                { <u8 as ::ink_core::storage::traits::SpreadLayout>::push_spread(&#index, __key_ptr); }
158
159
160
161
162
163
164
165
                #(
                    { #fields }
                )*
            }
        }
    });
    let clear_body = s.each(|field| {
        quote! {
166
            ::ink_core::storage::traits::SpreadLayout::clear_spread(#field, __key_ptr);
167
168
169
        }
    });
    s.gen_impl(quote! {
170
        gen impl ::ink_core::storage::traits::SpreadLayout for @Self {
171
172
173
174
175
            #[allow(unused_comparisons)]
            const FOOTPRINT: u64 = 1 + #footprint_body;

            const REQUIRES_DEEP_CLEAN_UP: bool = #requires_deep_clean_up_body;

176
177
            fn pull_spread(__key_ptr: &mut ::ink_core::storage::traits::KeyPtr) -> Self {
                match <u8 as ::ink_core::storage::traits::SpreadLayout>::pull_spread(__key_ptr) {
178
179
180
181
                    #pull_body
                    _ => unreachable!("encountered invalid enum discriminant"),
                }
            }
182
            fn push_spread(&self, __key_ptr: &mut ::ink_core::storage::traits::KeyPtr) {
183
184
185
186
187
188
                match self {
                    #(
                        #push_body
                    )*
                }
            }
189
            fn clear_spread(&self, __key_ptr: &mut ::ink_core::storage::traits::KeyPtr) {
190
191
192
193
194
195
196
197
198
199
                match self {
                    #clear_body
                }
            }
        }
    })
}

/// Derives `ink_core`'s `SpreadLayout` trait for the given `struct` or `enum`.
pub fn spread_layout_derive(mut s: synstructure::Structure) -> TokenStream2 {
200
201
202
    s.bind_with(|_| synstructure::BindStyle::Move)
        .add_bounds(synstructure::AddBounds::Generics)
        .underscore_const(true);
203
204
205
206
207
208
209
210
    match s.ast().data {
        syn::Data::Struct(_) => spread_layout_struct_derive(&s),
        syn::Data::Enum(_) => spread_layout_enum_derive(&s),
        _ => {
            panic!(
                "cannot derive `SpreadLayout` or `PackedLayout` for Rust `union` items"
            )
        }
211
212
    }
}