spread_layout.rs 7.35 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
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
// 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)
                .map(|ty| quote! { <#ty as ::ink_core::storage2::traits::SpreadLayout>::FOOTPRINT })
                .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)
            .map(|ty| quote! { <#ty as ::ink_core::storage2::traits::SpreadLayout>::REQUIRES_DEEP_CLEAN_UP })
            .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! {
            <#ty as ::ink_core::storage2::traits::SpreadLayout>::pull_spread(__key_ptr)
        }
    });
    let push_body = variant.each(|binding| {
        quote! {
            ::ink_core::storage2::traits::SpreadLayout::push_spread(#binding, __key_ptr);
        }
    });
    let clear_body = s.each(|field| {
        quote! {
            ::ink_core::storage2::traits::SpreadLayout::clear_spread(#field, __key_ptr);
        }
    });
    s.gen_impl(quote! {
        gen impl ::ink_core::storage2::traits::SpreadLayout for @Self {
            #[allow(unused_comparisons)]
            const FOOTPRINT: u64 = #footprint_body;
            const REQUIRES_DEEP_CLEAN_UP: bool = #requires_deep_clean_up_body;

            fn pull_spread(__key_ptr: &mut ::ink_core::storage2::traits::KeyPtr) -> Self {
                #pull_body
            }
            fn push_spread(&self, __key_ptr: &mut ::ink_core::storage2::traits::KeyPtr) {
                match self { #push_body }
            }
            fn clear_spread(&self, __key_ptr: &mut ::ink_core::storage2::traits::KeyPtr) {
                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! {
                    <#ty as ::ink_core::storage2::traits::SpreadLayout>::pull_spread(__key_ptr)
                }
            })
        })
        .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! {
                ::ink_core::storage2::traits::SpreadLayout::push_spread(#field, __key_ptr);
            }
        });
        quote! {
            #pat => {
                { <u8 as ::ink_core::storage2::traits::SpreadLayout>::push_spread(&#index, __key_ptr); }
                #(
                    { #fields }
                )*
            }
        }
    });
    let clear_body = s.each(|field| {
        quote! {
            ::ink_core::storage2::traits::SpreadLayout::clear_spread(#field, __key_ptr);
        }
    });
    s.gen_impl(quote! {
        gen impl ::ink_core::storage2::traits::SpreadLayout for @Self {
            #[allow(unused_comparisons)]
            const FOOTPRINT: u64 = 1 + #footprint_body;

            const REQUIRES_DEEP_CLEAN_UP: bool = #requires_deep_clean_up_body;

            fn pull_spread(__key_ptr: &mut ::ink_core::storage2::traits::KeyPtr) -> Self {
                match <u8 as ::ink_core::storage2::traits::SpreadLayout>::pull_spread(__key_ptr) {
                    #pull_body
                    _ => unreachable!("encountered invalid enum discriminant"),
                }
            }
            fn push_spread(&self, __key_ptr: &mut ::ink_core::storage2::traits::KeyPtr) {
                match self {
                    #(
                        #push_body
                    )*
                }
            }
            fn clear_spread(&self, __key_ptr: &mut ::ink_core::storage2::traits::KeyPtr) {
                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
    }
}