ink_codegen/generator/trait_def/
mod.rs

1// Copyright (C) Use Ink (UK) Ltd.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15mod call_builder;
16mod call_forwarder;
17mod definition;
18mod message_builder;
19mod trait_registry;
20
21use crate::GenerateCode;
22use derive_more::From;
23use proc_macro2::{
24    Span,
25    TokenStream as TokenStream2,
26};
27use quote::{
28    format_ident,
29    quote_spanned,
30};
31
32/// Generator to create the ink! storage struct and important trait implementations.
33#[derive(From, Copy, Clone)]
34pub struct TraitDefinition<'a> {
35    trait_def: &'a ir::InkTraitDefinition,
36}
37
38impl TraitDefinition<'_> {
39    /// Appends the trait suffix to the string and forms an identifier.
40    ///
41    /// This appends the `_$NAME_$TRAIT_ID` string to the prefix string
42    /// were `$NAME` is the non-unique name of the trait and `$TRAIT_ID`
43    /// is the hex representation of the unique 4-byte trait identifier.
44    fn append_trait_suffix(&self, prefix: &str) -> syn::Ident {
45        format_ident!("__ink_{}{}", prefix, self.trait_def.item().ident(),)
46    }
47
48    /// Returns the span of the underlying ink! trait definition.
49    fn span(&self) -> Span {
50        self.trait_def.item().span()
51    }
52}
53
54impl GenerateCode for TraitDefinition<'_> {
55    fn generate_code(&self) -> TokenStream2 {
56        let span = self.trait_def.item().span();
57        let trait_definition = self.generate_trait_definition();
58        let trait_registry = self.generate_trait_registry_impl();
59        let trait_message_builder = self.generate_message_builder();
60        let trait_call_builder = self.generate_call_builder();
61        let trait_call_forwarder = self.generate_call_forwarder();
62        quote_spanned!(span =>
63            #trait_definition
64            const _: () = {
65                #trait_registry
66                #trait_message_builder
67                #trait_call_builder
68                #trait_call_forwarder
69            };
70        )
71    }
72}