ink_macro/
scale.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
15use proc_macro2::TokenStream as TokenStream2;
16
17pub fn derive(attr: TokenStream2, item: TokenStream2) -> syn::Result<TokenStream2> {
18    let mut encode = false;
19    let mut decode = false;
20    let mut type_info = false;
21
22    syn::parse::Parser::parse2(
23        syn::meta::parser(|meta| {
24            if meta.path.is_ident("Encode") {
25                encode = true;
26                Ok(())
27            } else if meta.path.is_ident("Decode") {
28                decode = true;
29                Ok(())
30            } else if meta.path.is_ident("TypeInfo") {
31                type_info = true;
32                Ok(())
33            } else {
34                Err(meta.error(
35                    "unsupported scale derive: expected Encode, Decode or TypeInfo",
36                ))
37            }
38        }),
39        attr,
40    )?;
41
42    let codec_crate =
43        (encode || decode).then(|| quote::quote!(#[codec(crate = ::ink::scale)]));
44    let encode = encode.then(|| quote::quote!(#[derive(::ink::scale::Encode)]));
45    let decode = decode.then(|| quote::quote!(#[derive(::ink::scale::Decode)]));
46
47    let type_info = type_info.then(|| {
48        quote::quote!(
49            #[cfg_attr(
50                feature = "std",
51                derive(::ink::scale_info::TypeInfo),
52                scale_info(crate = ::ink::scale_info)
53            )]
54        )
55    });
56
57    Ok(quote::quote!(
58        #encode
59        #decode
60        #codec_crate
61        #type_info
62        #item
63    ))
64}