metadata.rs 14 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
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
//
// 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 crate::GenerateCode;
use derive_more::From;
use ir::Callable as _;
use proc_macro2::TokenStream as TokenStream2;
use quote::{
    quote,
    quote_spanned,
};
use syn::spanned::Spanned as _;

/// Generates code to generate the metadata of the contract.
#[derive(From)]
pub struct Metadata<'a> {
    /// The contract to generate code for.
    contract: &'a ir::Contract,
}

impl GenerateCode for Metadata<'_> {
    fn generate_code(&self) -> TokenStream2 {
        let contract = self.generate_contract();
        let layout = self.generate_layout();

        quote! {
            #[cfg(feature = "std")]
            #[cfg(not(feature = "ink-as-dependency"))]
            const _: () = {
                #[no_mangle]
                pub fn __ink_generate_metadata() -> ::ink_metadata::InkProject  {
                    let contract: ::ink_metadata::ContractSpec = {
                        #contract
                    };
46
                    let layout: ::ink_metadata::layout::Layout = {
47
48
49
50
51
52
53
54
55
56
57
58
59
                        #layout
                    };
                    ::ink_metadata::InkProject::new(layout, contract)
                }
            };
        }
    }
}

impl Metadata<'_> {
    fn generate_layout(&self) -> TokenStream2 {
        let contract_ident = self.contract.module().storage().ident();
        quote! {
60
            <#contract_ident as ::ink_storage::traits::StorageLayout>::layout(
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
                &mut ::ink_primitives::KeyPtr::from(::ink_primitives::Key::from([0x00; 32]))
            )
        }
    }

    fn generate_contract(&self) -> TokenStream2 {
        let constructors = self.generate_constructors();
        let messages = self.generate_messages();
        let events = self.generate_events();
        let docs = self.generate_docs();

        quote! {
            ::ink_metadata::ContractSpec::new()
                .constructors(vec![
                    #(#constructors ,)*
                ])
                .messages(vec![
                    #(#messages ,)*
                ])
                .events(vec![
                    #(#events ,)*
                ])
                .docs(vec![
                    #(#docs ,)*
                ])
                .done()
        }
    }

    /// Extracts the doc strings from the given slice of attributes.
91
92
93
    fn extract_doc_comments(
        attributes: &[syn::Attribute],
    ) -> impl Iterator<Item = String> + '_ {
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
        attributes
            .iter()
            .filter_map(|attribute| {
                match attribute.parse_meta() {
                    Ok(syn::Meta::NameValue(name_value)) => Some(name_value),
                    Ok(_) | Err(_) => None,
                }
            })
            .filter(|name_value| name_value.path.is_ident("doc"))
            .filter_map(|name_value| {
                match name_value.lit {
                    syn::Lit::Str(lit_str) => Some(lit_str.value()),
                    _ => None,
                }
            })
    }

    /// Generates ink! metadata for all contract constructors.
112
    fn generate_constructors(&self) -> impl Iterator<Item = TokenStream2> + '_ {
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
        self.contract
            .module()
            .impls()
            .flat_map(|impl_block| {
                let trait_ident = impl_block
                    .trait_path()
                    .map(|path| path.segments.last().map(|seg| &seg.ident))
                    .flatten();
                impl_block
                    .iter_constructors()
                    .map(move |constructor| (trait_ident, constructor))
            })
            .map(|(trait_ident, constructor)| {
                let span = constructor.span();
                let attrs = constructor.attrs();
128
                let docs = Self::extract_doc_comments(attrs);
129
130
131
132
133
134
135
136
137
138
139
                let selector = constructor.composed_selector();
                let selector_bytes = selector.as_bytes();
                let constructor = constructor.callable();
                let ident = constructor.ident();
                let ident_lit = ident.to_string();
                let args = constructor
                    .inputs()
                    .map(|arg| Self::generate_message_param(arg));
                let constr = match trait_ident {
                    Some(trait_ident) => {
                        let trait_ident_lit = trait_ident.to_string();
Andrew Jones's avatar
Andrew Jones committed
140
                        quote_spanned!(span => from_trait_and_name(#trait_ident_lit, #ident_lit))
141
142
                    }
                    None => {
Andrew Jones's avatar
Andrew Jones committed
143
                        quote_spanned!(span => from_name(#ident_lit))
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
                    }
                };
                quote_spanned!(span =>
                    ::ink_metadata::ConstructorSpec::#constr
                        .selector([#(#selector_bytes),*])
                        .args(vec![
                            #(#args ,)*
                        ])
                        .docs(vec![
                            #(#docs ,)*
                        ])
                        .done()
                )
            })
    }

    /// Generates the ink! metadata for the given parameter and parameter type.
    fn generate_message_param(pat_type: &syn::PatType) -> TokenStream2 {
        let ident = match &*pat_type.pat {
            syn::Pat::Ident(ident) => &ident.ident,
            _ => unreachable!("encountered unexpected non identifier in ink! parameter"),
        };
        let ident_lit = ident.to_string();
        let type_spec = Self::generate_type_spec(&pat_type.ty);
        quote! {
            ::ink_metadata::MessageParamSpec::new(#ident_lit)
                .of_type(#type_spec)
                .done()
        }
    }

    /// Generates the ink! metadata for the given type.
    fn generate_type_spec(ty: &syn::Type) -> TokenStream2 {
        fn without_display_name(ty: &syn::Type) -> TokenStream2 {
            quote! { ::ink_metadata::TypeSpec::new::<#ty>() }
        }
        if let syn::Type::Path(type_path) = ty {
            if type_path.qself.is_some() {
                return without_display_name(ty)
            }
            let path = &type_path.path;
            if path.segments.is_empty() {
                return without_display_name(ty)
            }
            let segs = path
                .segments
                .iter()
                .map(|seg| seg.ident.to_string())
                .collect::<Vec<_>>();
            quote! {
                ::ink_metadata::TypeSpec::with_name_segs::<#ty, _>(
                    vec![#(#segs),*].into_iter().map(AsRef::as_ref)
                )
            }
        } else {
            without_display_name(ty)
        }
    }

203
    fn generate_messages(&self) -> impl Iterator<Item = TokenStream2> + '_ {
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
        self.contract
            .module()
            .impls()
            .flat_map(|impl_block| {
                let trait_ident = impl_block
                    .trait_path()
                    .map(|path| path.segments.last().map(|seg| &seg.ident))
                    .flatten();
                impl_block
                    .iter_messages()
                    .map(move |message| (trait_ident, message))
            })
            .map(|(trait_ident, message)| {
                let span = message.span();
                let attrs = message.attrs();
219
                let docs = Self::extract_doc_comments(attrs);
220
221
222
223
224
225
226
227
228
229
230
231
232
233
                let selector = message.composed_selector();
                let selector_bytes = selector.as_bytes();
                let is_payable = message.is_payable();
                let message = message.callable();
                let mutates = message.receiver().is_ref_mut();
                let ident = message.ident();
                let ident_lit = ident.to_string();
                let args = message
                    .inputs()
                    .map(|arg| Self::generate_message_param(arg));
                let ret_ty = Self::generate_return_type(message.output());
                let constr = match trait_ident {
                    Some(trait_ident) => {
                        let trait_ident_lit = trait_ident.to_string();
Andrew Jones's avatar
Andrew Jones committed
234
                        quote_spanned!(span => from_trait_and_name(#trait_ident_lit, #ident_lit))
235
236
                    }
                    None => {
Andrew Jones's avatar
Andrew Jones committed
237
                        quote_spanned!(span => from_name(#ident_lit))
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
                    }
                };
                quote_spanned!(span =>
                    ::ink_metadata::MessageSpec::#constr
                        .selector([#(#selector_bytes),*])
                        .args(vec![
                            #(#args ,)*
                        ])
                        .returns(#ret_ty)
                        .mutates(#mutates)
                        .payable(#is_payable)
                        .docs(vec![
                            #(#docs ,)*
                        ])
                        .done()
                )
            })
    }

    /// Generates ink! metadata for the given return type.
    fn generate_return_type(ret_ty: Option<&syn::Type>) -> TokenStream2 {
        match ret_ty {
            None => {
                quote! {
                    ::ink_metadata::ReturnTypeSpec::new(None)
                }
            }
            Some(ty) => {
                let type_spec = Self::generate_type_spec(ty);
                quote! {
                    ::ink_metadata::ReturnTypeSpec::new(#type_spec)
                }
            }
        }
    }

    /// Generates ink! metadata for all user provided ink! event definitions.
275
    fn generate_events(&self) -> impl Iterator<Item = TokenStream2> + '_ {
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
        self.contract.module().events().map(|event| {
            let span = event.span();
            let ident = event.ident();
            let ident_lit = ident.to_string();
            let docs = Self::extract_doc_comments(event.attrs());
            let args = Self::generate_event_args(event);
            quote_spanned!(span =>
                ::ink_metadata::EventSpec::new(#ident_lit)
                    .args(vec![
                        #( #args, )*
                    ])
                    .docs(vec![
                        #( #docs, )*
                    ])
                    .done()
            )
        })
    }

    /// Generate ink! metadata for a single argument of an ink! event definition.
296
    fn generate_event_args(event: &ir::Event) -> impl Iterator<Item = TokenStream2> + '_ {
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
        event.fields().map(|event_field| {
            let span = event_field.span();
            let ident = event_field.ident();
            let ident_lit = ident.map(ToString::to_string);
            let is_topic = event_field.is_topic;
            let attrs = event_field.attrs();
            let docs = Self::extract_doc_comments(&attrs);
            let ty = Self::generate_type_spec(event_field.ty());
            quote_spanned!(span =>
                ::ink_metadata::EventParamSpec::new(#ident_lit)
                    .of_type(#ty)
                    .indexed(#is_topic)
                    .docs(vec![
                        #( #docs, )*
                    ])
                    .done()
            )
        })
    }

    /// Generates the documentation for the contract module.
318
    fn generate_docs(&self) -> impl Iterator<Item = String> + '_ {
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
        Self::extract_doc_comments(self.contract.module().attrs())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn extract_doc_comments_works() {
        assert_eq!(
            Metadata::extract_doc_comments(&[syn::parse_quote!( #[doc = r"content"] )])
                .collect::<Vec<_>>(),
            vec!["content".to_string()],
        );
        assert_eq!(
            Metadata::extract_doc_comments(&[syn::parse_quote!(
                /// content
            )])
            .collect::<Vec<_>>(),
            vec![" content".to_string()],
        );
        assert_eq!(
            Metadata::extract_doc_comments(&[syn::parse_quote!(
                /**
                 * Multi-line comments ...
                 * May span many lines
                 */
            )])
            .collect::<Vec<_>>(),
            vec![r"
                 * Multi-line comments ...
                 * May span many lines
                 "
            .to_string()],
        );
        assert_eq!(
            Metadata::extract_doc_comments(&[
                syn::parse_quote!(
                    /// multiple
                ),
                syn::parse_quote!(
                    /// single
                ),
                syn::parse_quote!(
                    /// line
                ),
                syn::parse_quote!(
                    /// commments
                ),
            ])
            .collect::<Vec<_>>(),
            vec![
                " multiple".to_string(),
                " single".to_string(),
                " line".to_string(),
                " commments".to_string(),
            ],
        );
        assert_eq!(
            Metadata::extract_doc_comments(&[
                syn::parse_quote!( #[doc = r"a"] ),
                syn::parse_quote!( #[non_doc] ),
                syn::parse_quote!( #[doc = r"b"] ),
                syn::parse_quote!( #[derive(NonDoc)] ),
                syn::parse_quote!( #[doc = r"c"] ),
                syn::parse_quote!( #[docker = false] ),
                syn::parse_quote!( #[doc = r"d"] ),
                syn::parse_quote!( #[doc(Nope)] ),
                syn::parse_quote!( #[doc = r"e"] ),
            ])
            .collect::<Vec<_>>(),
            vec![
                "a".to_string(),
                "b".to_string(),
                "c".to_string(),
                "d".to_string(),
                "e".to_string(),
            ],
        )
    }
}