ink_codegen 5.1.1

data structures and algorithms for generating ink! IR code
Documentation
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
// Copyright (C) Use Ink (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 super::TraitDefinition;
use crate::{
    generator,
    traits::GenerateCode,
};
use derive_more::From;
use proc_macro2::{
    Span,
    TokenStream as TokenStream2,
};
use quote::{
    quote,
    quote_spanned,
};

impl<'a> TraitDefinition<'a> {
    /// Generates code for the global trait call forwarder for an ink! trait.
    ///
    /// # Note
    ///
    /// - The generated call forwarder type implements the ink! trait definition and
    ///   allows to build up contract calls that allow for customization by the user to
    ///   provide gas limit, endowment etc.
    /// - The call forwarder is associated to the call builder for the same ink! trait
    ///   definition and handles all ink! trait calls into another contract instance
    ///   on-chain. For constructing custom calls it forwards to the call builder.
    pub fn generate_call_forwarder(&self) -> TokenStream2 {
        CallForwarder::from(*self).generate_code()
    }

    /// The identifier of the ink! trait call forwarder.
    pub fn call_forwarder_ident(&self) -> syn::Ident {
        self.append_trait_suffix(CallForwarder::SUFFIX)
    }
}

/// Generates code for the global ink! trait call forwarder.
#[derive(From)]
struct CallForwarder<'a> {
    trait_def: TraitDefinition<'a>,
}

impl GenerateCode for CallForwarder<'_> {
    fn generate_code(&self) -> TokenStream2 {
        let struct_definition = self.generate_struct_definition();
        let storage_layout_impl = self.generate_storage_layout_impl();
        let auxiliary_trait_impls = self.generate_auxiliary_trait_impls();
        let to_from_account_id_impls = self.generate_to_from_account_id_impls();
        let call_builder_impl = self.generate_call_builder_trait_impl();
        let ink_trait_impl = self.generate_ink_trait_impl();
        quote! {
            #struct_definition
            #storage_layout_impl
            #auxiliary_trait_impls
            #to_from_account_id_impls
            #call_builder_impl
            #ink_trait_impl
        }
    }
}

impl CallForwarder<'_> {
    /// The name suffix for ink! trait call forwarder.
    const SUFFIX: &'static str = "TraitCallForwarder";

    /// Returns the span of the ink! trait definition.
    fn span(&self) -> Span {
        self.trait_def.span()
    }

    /// Returns the identifier of the ink! trait call forwarder.
    fn ident(&self) -> syn::Ident {
        self.trait_def.call_forwarder_ident()
    }

    /// Generates the struct type definition for the account wrapper type.
    ///
    /// This type is going to implement the trait so that invoking its trait
    /// methods will perform contract calls via contract's pallet contract
    /// execution abstraction.
    ///
    /// # Note
    ///
    /// Unlike the layout specific traits it is possible to derive the SCALE
    /// `Encode` and `Decode` traits since they generate trait bounds per field
    /// instead of per generic parameter which is exactly what we need here.
    /// However, it should be noted that this is not Rust default behavior.
    fn generate_struct_definition(&self) -> TokenStream2 {
        let span = self.span();
        let call_forwarder_ident = self.ident();
        quote_spanned!(span =>
            /// The global call forwarder for the ink! trait definition.
            ///
            /// All cross-contract calls to contracts implementing the associated ink! trait
            /// will be handled by this type.
            #[doc(hidden)]
            #[allow(non_camel_case_types)]
            #[::ink::scale_derive(Encode, Decode)]
            #[repr(transparent)]
            pub struct #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
            {
                builder: <Self as ::ink::codegen::TraitCallBuilder>::Builder,
            }
        )
    }

    /// Generates the `StorageLayout` trait implementation for the account wrapper.
    ///
    /// # Note
    ///
    /// Due to the generic parameter `E` and Rust's default rules for derive generated
    /// trait bounds it is not recommended to derive the `StorageLayout` trait
    /// implementation.
    fn generate_storage_layout_impl(&self) -> TokenStream2 {
        let span = self.span();
        let call_forwarder_ident = self.ident();
        quote_spanned!(span=>
            #[cfg(feature = "std")]
            impl<E> ::ink::storage::traits::StorageLayout
                for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
                <E as ::ink::env::Environment>::AccountId: ::ink::storage::traits::StorageLayout,
            {
                fn layout(
                    __key: &::ink::primitives::Key,
                ) -> ::ink::metadata::layout::Layout {
                    <<Self as ::ink::codegen::TraitCallBuilder>::Builder
                        as ::ink::storage::traits::StorageLayout>::layout(__key)
                }
            }
        )
    }

    /// Generates trait implementations for auxiliary traits for the account wrapper.
    ///
    /// # Note
    ///
    /// Auxiliary traits currently include:
    ///
    /// - `Clone`: To allow cloning contract references in the long run.
    /// - `Debug`: To better debug internal contract state.
    fn generate_auxiliary_trait_impls(&self) -> TokenStream2 {
        let span = self.span();
        let call_forwarder_ident = self.ident();
        quote_spanned!(span=>
            /// We require this manual implementation since the derive produces incorrect trait bounds.
            impl<E> ::core::clone::Clone for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
                <E as ::ink::env::Environment>::AccountId: ::core::clone::Clone,
            {
                #[inline]
                fn clone(&self) -> Self {
                    Self {
                        builder: <<Self as ::ink::codegen::TraitCallBuilder>::Builder
                            as ::core::clone::Clone>::clone(&self.builder),
                    }
                }
            }

            /// We require this manual implementation since the derive produces incorrect trait bounds.
            impl<E> ::core::fmt::Debug for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
                <E as ::ink::env::Environment>::AccountId: ::core::fmt::Debug,
            {
                fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
                    f.debug_struct(::core::stringify!(#call_forwarder_ident))
                        .field("account_id", &self.builder.account_id)
                        .finish()
                }
            }

            #[cfg(feature = "std")]
            /// We require this manual implementation since the derive produces incorrect trait bounds.
            impl<E> ::ink::scale_info::TypeInfo for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
                <E as ::ink::env::Environment>::AccountId: ::ink::scale_info::TypeInfo + 'static,
            {
                type Identity = <
                    <Self as ::ink::codegen::TraitCallBuilder>::Builder as ::ink::scale_info::TypeInfo
                >::Identity;

                fn type_info() -> ::ink::scale_info::Type {
                    <
                        <Self as ::ink::codegen::TraitCallBuilder>::Builder as ::ink::scale_info::TypeInfo
                    >::type_info()
                }
            }
        )
    }

    /// Generate trait impls for `FromAccountId` and `ToAccountId` for the account
    /// wrapper.
    ///
    /// # Note
    ///
    /// This allows user code to conveniently transform from and to `AccountId` when
    /// interacting with typed contracts.
    fn generate_to_from_account_id_impls(&self) -> TokenStream2 {
        let span = self.span();
        let call_forwarder_ident = self.ident();
        quote_spanned!(span=>
            impl<E> ::ink::env::call::FromAccountId<E>
                for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
            {
                #[inline]
                fn from_account_id(account_id: <E as ::ink::env::Environment>::AccountId) -> Self {
                    Self { builder: <<Self as ::ink::codegen::TraitCallBuilder>::Builder
                        as ::ink::env::call::FromAccountId<E>>::from_account_id(account_id) }
                }
            }

            impl<E, AccountId> ::core::convert::From<AccountId> for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment<AccountId = AccountId>,
                AccountId: ::ink::env::AccountIdGuard,
            {
                fn from(value: AccountId) -> Self {
                    <Self as ::ink::env::call::FromAccountId<E>>::from_account_id(value)
                }
            }

            impl<E> ::ink::ToAccountId<E> for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
            {
                #[inline]
                fn to_account_id(&self) -> <E as ::ink::env::Environment>::AccountId {
                    <<Self as ::ink::codegen::TraitCallBuilder>::Builder
                        as ::ink::ToAccountId<E>>::to_account_id(&self.builder)
                }
            }

            impl<E, AccountId> ::core::convert::AsRef<AccountId> for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment<AccountId = AccountId>,
            {
                fn as_ref(&self) -> &AccountId {
                    <_ as ::core::convert::AsRef<AccountId>>::as_ref(&self.builder)
                }
            }

            impl<E, AccountId> ::core::convert::AsMut<AccountId> for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment<AccountId = AccountId>,
            {
                fn as_mut(&mut self) -> &mut AccountId {
                    <_ as ::core::convert::AsMut<AccountId>>::as_mut(&mut self.builder)
                }
            }
        )
    }

    /// Generate the trait implementation for `CallBuilder` for the ink! trait call
    /// forwarder.
    ///
    /// # Note
    ///
    /// Through the implementation of this trait it is possible to refer to the
    /// ink! trait call builder that is associated to this ink! trait call forwarder.
    fn generate_call_builder_trait_impl(&self) -> TokenStream2 {
        let span = self.trait_def.span();
        let call_forwarder_ident = self.ident();
        let call_builder_ident = self.trait_def.call_builder_ident();
        quote_spanned!(span=>
            /// This trait allows to bridge from call forwarder to call builder.
            ///
            /// Also this explains why we designed the generated code so that we have
            /// both types and why the forwarder is a thin-wrapper around the builder
            /// as this allows to perform this operation safely.
            impl<E> ::ink::codegen::TraitCallBuilder for #call_forwarder_ident<E>
            where
                E: ::ink::env::Environment,
            {
                type Builder = #call_builder_ident<E>;

                #[inline]
                fn call(&self) -> &<Self as ::ink::codegen::TraitCallBuilder>::Builder {
                    &self.builder
                }

                #[inline]
                fn call_mut(&mut self) -> &mut <Self as ::ink::codegen::TraitCallBuilder>::Builder {
                    &mut self.builder
                }
            }
        )
    }

    /// Generates the implementation of the associated ink! trait definition.
    ///
    /// # Note
    ///
    /// The implementation mainly forwards to the associated ink! call builder
    /// of the same ink! trait definition.
    fn generate_ink_trait_impl(&self) -> TokenStream2 {
        let span = self.trait_def.span();
        let trait_ident = self.trait_def.trait_def.item().ident();
        let trait_info_ident = self.trait_def.trait_info_ident();
        let forwarder_ident = self.ident();
        let message_impls = self.generate_ink_trait_impl_messages();
        quote_spanned!(span=>
            impl<E> ::ink::env::ContractEnv for #forwarder_ident<E>
            where
                E: ::ink::env::Environment,
            {
                type Env = E;
            }

            impl<E> #trait_ident for #forwarder_ident<E>
            where
                E: ::ink::env::Environment,
            {
                #[allow(non_camel_case_types)]
                type __ink_TraitInfo = #trait_info_ident<E>;

                #message_impls
            }
        )
    }

    /// Generate the code for all ink! trait messages implemented by the trait call
    /// forwarder.
    fn generate_ink_trait_impl_messages(&self) -> TokenStream2 {
        let messages =
            self.trait_def
                .trait_def
                .item()
                .iter_items()
                .filter_map(|(item, _)| {
                    item.filter_map_message()
                        .map(|message| self.generate_ink_trait_impl_for_message(&message))
                });
        quote! {
            #( #messages )*
        }
    }

    /// Generate the code for a single ink! trait message implemented by the trait call
    /// forwarder.
    fn generate_ink_trait_impl_for_message(
        &self,
        message: &ir::InkTraitMessage,
    ) -> TokenStream2 {
        let span = message.span();
        let trait_ident = self.trait_def.trait_def.item().ident();
        let forwarder_ident = self.ident();
        let message_ident = message.ident();
        let attrs = self
            .trait_def
            .trait_def
            .config()
            .whitelisted_attributes()
            .filter_attr(message.attrs());
        let output_ident = generator::output_ident(message_ident);
        let output_type = message
            .output()
            .cloned()
            .unwrap_or_else(|| syn::parse_quote!(()));
        let input_bindings = message.inputs().map(|input| &input.pat).collect::<Vec<_>>();
        let input_types = message.inputs().map(|input| &input.ty).collect::<Vec<_>>();
        let call_op = match message.receiver() {
            ir::Receiver::Ref => quote! { call },
            ir::Receiver::RefMut => quote! { call_mut },
        };
        let mut_tok = message.mutates().then(|| quote! { mut });
        let panic_str = format!(
            "encountered error while calling <{forwarder_ident} as {trait_ident}>::{message_ident}",
        );
        let cfg_attrs = message.get_cfg_attrs(span);
        quote_spanned!(span =>
            #( #cfg_attrs )*
            type #output_ident = #output_type;

            #( #attrs )*
            #[inline]
            fn #message_ident(
                & #mut_tok self
                #( , #input_bindings : #input_types )*
            ) -> Self::#output_ident {
                <<Self as ::ink::codegen::TraitCallBuilder>::Builder as #trait_ident>::#message_ident(
                    <Self as ::ink::codegen::TraitCallBuilder>::#call_op(self)
                    #(
                        , #input_bindings
                    )*
                )
                    .try_invoke()
                    .unwrap_or_else(|env_err| ::core::panic!("{}: {:?}", #panic_str, env_err))
                    .unwrap_or_else(|lang_err| ::core::panic!("{}: {:?}", #panic_str, lang_err))
            }
        )
    }
}