storage.rs 11.5 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// Copyright 2018-2019 Parity Technologies (UK) Ltd.
// This file is part of ink!.
//
// ink! is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ink! is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with ink!.  If not, see <http://www.gnu.org/licenses/>.

use crate::{
18
    codegen::{
Robin Freyler's avatar
Robin Freyler committed
19
        cross_calling::CrossCallingConflictCfg,
20 21 22
        GenerateCode,
        GenerateCodeUsing,
    },
23
    ir::{
24
        self,
25
        utils,
26
        Contract,
27
        Function,
28 29 30 31
    },
};
use derive_more::From;
use proc_macro2::TokenStream as TokenStream2;
32 33 34 35
use quote::{
    quote,
    quote_spanned,
};
36 37 38 39 40 41

#[derive(From)]
pub struct Storage<'a> {
    contract: &'a Contract,
}

42 43 44 45 46 47
impl<'a> GenerateCodeUsing for Storage<'a> {
    fn contract(&self) -> &ir::Contract {
        self.contract
    }
}

48 49 50 51
impl GenerateCode for Storage<'_> {
    fn generate_code(&self) -> TokenStream2 {
        let storage_span = self.contract.storage.span();

52
        let conflic_depedency_cfg = self.generate_code_using::<CrossCallingConflictCfg>();
53 54 55 56 57 58
        let aliases = self.generate_aliases();
        let trait_impls = self.generate_trait_impls_for_storage();
        let access_env_impls = self.generate_access_env_trait_impls();
        let message_impls = self.generate_message_impls();
        let storage_struct = self.generate_storage_struct();
        let storage_and_env_wrapper = self.generate_storage_and_env_wrapper();
59
        let layout_impls = self.generate_has_layout();
60

61 62
        let use_emit_event = if !self.contract.events.is_empty() {
            // Required to allow for `self.env().emit_event(..)` in messages and constructors.
63
            quote! { use __ink_private::EmitEvent as _; }
64 65 66 67
        } else {
            quote! {}
        };

68 69
        quote_spanned!(storage_span =>
            #[doc(hidden)]
70
            #conflic_depedency_cfg
71 72 73 74 75 76 77 78
            mod __ink_storage {
                use super::*;

                #aliases
                #access_env_impls
                #trait_impls
                #storage_struct
                #storage_and_env_wrapper
79
                #layout_impls
80
            }
81

82
            #conflic_depedency_cfg
83
            pub use __ink_storage::StorageAndEnv;
84

85
            #conflic_depedency_cfg
86 87 88 89 90
            const _: () = {
                // Used to make `self.env()` available in message code.
                #[allow(unused_imports)]
                use ink_core::env2::AccessEnv as _;

91
                #use_emit_event
92 93
                #message_impls
            };
94 95
        )
    }
96 97
}

98
impl Storage<'_> {
99
    fn generate_access_env_trait_impls(&self) -> TokenStream2 {
100 101
        let access_env_impls = if self.contract.meta_info.is_dynamic_allocation_enabled()
        {
102 103
            quote! {
                impl ink_lang2::AccessEnv<Env> for StorageAndEnv {
104
                    fn access_env(&mut self) -> &mut ink_core::env2::EnvAccess<Env> {
105
                        self.__env.env_mut()
106 107 108 109 110 111
                    }
                }
            }
        } else {
            quote! {
                impl ink_lang2::AccessEnv<Env> for StorageAndEnv {
112
                    fn access_env(&mut self) -> &mut ink_core::env2::EnvAccess<Env> {
113 114 115 116 117 118 119
                        &mut self.__env
                    }
                }
            }
        };
        quote! {
            #access_env_impls
120

121 122 123 124
            impl<'a> ink_core::env2::AccessEnv for &'a StorageAndEnv {
                type Target = <&'a UsedEnv as ink_core::env2::AccessEnv>::Target;

                fn env(self) -> Self::Target {
125
                    ink_core::env2::AccessEnv::env(&self.__env)
126
                }
127
            }
128 129 130 131 132

            impl<'a> ink_core::env2::AccessEnv for &'a mut StorageAndEnv {
                type Target = <&'a mut UsedEnv as ink_core::env2::AccessEnv>::Target;

                fn env(self) -> Self::Target {
133
                    ink_core::env2::AccessEnv::env(&mut self.__env)
134 135 136
                }
            }
        }
137 138
    }

139 140 141 142 143 144 145 146 147 148 149
    fn generate_aliases(&self) -> TokenStream2 {
        if self.contract.meta_info.is_dynamic_allocation_enabled() {
            quote! {
                pub type UsedEnv = ink_core::env2::DynEnv<ink_core::env2::EnvAccess<Env>>;
            }
        } else {
            quote! {
                pub type UsedEnv = ink_core::env2::EnvAccess<Env>;
            }
        }
    }
150

151 152 153 154 155 156
    fn generate_trait_impls_for_storage(&self) -> TokenStream2 {
        let field_idents = &self
            .contract
            .storage
            .fields
            .named
157
            .iter()
158 159
            .map(|named_field| &named_field.ident)
            .collect::<Vec<_>>();
160

161 162
        quote! {
            impl ink_core::storage::alloc::AllocateUsing for Storage {
163
                unsafe fn allocate_using<A>(alloc: &mut A) -> Self
164
                where
165
                    A: ink_core::storage::alloc::Allocate,
166 167 168
                {
                    Self {
                        #(
169
                            #field_idents: ink_core::storage::alloc::AllocateUsing::allocate_using(alloc),
170 171 172 173 174
                        )*
                    }
                }
            }

175
            impl ink_core::storage::Flush for Storage {
176 177
                fn flush(&mut self) {
                    #(
178
                        ink_core::storage::Flush::flush(&mut self.#field_idents);
179 180 181 182
                    )*
                }
            }

183
            impl ink_core::storage::alloc::Initialize for Storage {
184 185 186 187 188 189
                type Args = ();

                fn default_value() -> Option<Self::Args> {
                    Some(())
                }

190
                fn initialize(&mut self, _args: Self::Args) {
191
                    #(
192
                        self.#field_idents.try_default_initialize();
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
    fn generate_has_layout(&self) -> TokenStream2 {
        let env_layout = if self.contract.meta_info.is_dynamic_allocation_enabled() {
            quote! { ink_abi::LayoutField::new("env", self.__env.layout()), }
        } else {
            quote! {}
        };
        quote! {
            #[cfg(feature = "ink-generate-abi")]
            impl ink_abi::HasLayout for StorageAndEnv {
                fn layout(&self) -> ink_abi::StorageLayout {
                    use type_metadata::Metadata as _;
                    ink_abi::LayoutStruct::new(
                        Self::meta_type(),
                        vec![
                            ink_abi::LayoutField::new("storage", self.__storage.layout()),
                            #env_layout
                        ],
                    )
                    .into()
                }
            }

        }
    }

224
    fn generate_storage_and_env_wrapper(&self) -> TokenStream2 {
225
        let attrs = utils::filter_non_ink_attributes(&self.contract.storage.attrs);
226

227
        quote! {
228
            #(#attrs)*
229 230
            #[cfg_attr(
                feature = "ink-generate-abi",
231
                derive(type_metadata::Metadata)
232
            )]
233
            #[cfg_attr(any(test, feature = "test-env"), derive(Debug))]
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
            pub struct StorageAndEnv {
                __storage: Storage,
                __env: UsedEnv,
            }

            impl core::ops::Deref for StorageAndEnv {
                type Target = Storage;

                fn deref(&self) -> &Self::Target {
                    &self.__storage
                }
            }

            impl core::ops::DerefMut for StorageAndEnv {
                fn deref_mut(&mut self) -> &mut Self::Target {
                    &mut self.__storage
                }
            }

            impl ink_core::storage::alloc::AllocateUsing for StorageAndEnv {
                unsafe fn allocate_using<A>(alloc: &mut A) -> Self
                where
                    A: ink_core::storage::alloc::Allocate,
                {
                    Self {
                        __storage: ink_core::storage::alloc::AllocateUsing::allocate_using(alloc),
                        __env: ink_core::storage::alloc::AllocateUsing::allocate_using(alloc),
                    }
                }
            }

            impl ink_core::storage::Flush for StorageAndEnv {
                fn flush(&mut self) {
267 268
                    ink_core::storage::Flush::flush(&mut self.__storage);
                    ink_core::storage::Flush::flush(&mut self.__env);
269 270 271
                }
            }

272 273


274 275 276 277 278 279 280 281
            impl ink_core::storage::alloc::Initialize for StorageAndEnv {
                type Args = ();

                fn default_value() -> Option<Self::Args> {
                    Some(())
                }

                fn initialize(&mut self, _args: Self::Args) {
282 283
                    ink_core::storage::alloc::Initialize::try_default_initialize(&mut self.__storage);
                    ink_core::storage::alloc::Initialize::try_default_initialize(&mut self.__env);
284 285 286 287 288 289 290 291 292 293 294
                }
            }

            impl ink_lang2::Storage for StorageAndEnv {}
        }
    }

    /// Generates the storage struct definition.
    fn generate_storage_struct(&self) -> TokenStream2 {
        let storage = &self.contract.storage;
        let span = storage.span();
295
        let attrs = utils::filter_non_ink_attributes(&storage.attrs);
296
        let mut fields = storage.fields.clone();
Robin Freyler's avatar
Robin Freyler committed
297 298 299 300 301
        fields.named.iter_mut().for_each(|field| {
            field.vis = syn::Visibility::Public(syn::VisPublic {
                pub_token: Default::default(),
            })
        });
302 303 304

        quote_spanned!( span =>
            #(#attrs)*
305 306 307 308
            #[cfg_attr(
                feature = "ink-generate-abi",
                derive(type_metadata::Metadata, ink_abi::HasLayout)
            )]
309
            #[cfg_attr(any(test, feature = "test-env"), derive(Debug))]
310 311
            pub struct Storage
                #fields
312 313
        )
    }
314

315 316
    /// Generate a single message defined on the storage struct.
    fn generate_message(&self, function: &Function) -> TokenStream2 {
317 318 319 320 321 322 323
        let span = function.span();
        // Generate `pub` functions for constructors and messages only.
        let vis = if function.is_constructor() || function.is_message() {
            quote_spanned!(span => pub)
        } else {
            quote_spanned!(span => )
        };
324
        let attrs = utils::filter_non_ink_attributes(&self.contract.storage.attrs);
325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340
        let ident = &function.sig.ident;
        let (_, type_generics, where_clause) = function.sig.generics.split_for_impl();
        let inputs = &function.sig.inputs;
        let output = &function.sig.output;
        let block = &function.block;
        quote_spanned!( span =>
            #( #attrs )*
            #vis fn #ident #type_generics (
                #inputs,
            ) #output
            #where_clause
            #block
        )
    }

    /// Generates all the constructors, messages and methods defined on the storage struct.
341
    fn generate_message_impls(&self) -> TokenStream2 {
342 343 344 345 346 347
        let storage = &self.contract.storage;
        let span = storage.span();
        let fns = self
            .contract
            .functions
            .iter()
348
            .map(|fun| self.generate_message(fun));
349
        quote_spanned!( span =>
350
            impl StorageAndEnv {
351 352 353 354 355 356
                #(
                    #fns
                )*
            }
        )
    }
357
}