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
use proc_macro::TokenStream;
use proc_macro2::TokenTree;
use quote::quote;
use syn::{parse_macro_input, DeriveInput, Expr, Lit, Meta};

/// Implements following traits from `cw_iper_test` crate:
/// - `IbcPortInterface`
#[proc_macro_derive(IbcPort, attributes(ibc_port))]
pub fn derive_ibc_port(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let struct_name = &input.ident;

    let port = get_attr("ibc_port", &input.attrs).expect("ibc_port attribute not found");

    let mut f: String = "".to_string();

    if let Meta::NameValue(a) = &port.meta {
        if let Expr::Lit(b) = &a.value {
            if let Lit::Str(c) = &b.lit {
                f = c.value();
            }
        }
    };

    if f == *"" {
        panic!("port attributes not in corrected format. Requested in format #[port = 'port']")
    }

    let prepath = prepath();

    let expanded = quote! {
        impl #struct_name {
            /// Ibc port name
            pub const IBC_PORT: &'static str = #f;
        }
        impl #prepath::IbcPortInterface for #struct_name {
            fn port_name(&self) -> String {
                #f.to_string()
            }
        }
    };

    TokenStream::from(expanded)
}

/// Implements following traits from `cw_iper_test` crate:
/// - `StargateUrls`
/// - `StargateName`
#[proc_macro_derive(Stargate, attributes(stargate))]
pub fn derive_stargate(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let struct_name = &input.ident;

    let attributes = get_attr("stargate", &input.attrs).expect("stargate attribute not found");

    let mut query = None;

    let mut msgs = None;

    let mut name = None;

    if let Meta::List(list) = &attributes.meta {
        for (index, token) in list.tokens.clone().into_iter().enumerate() {
            if let TokenTree::Ident(ident) = token {
                if ident == "name" {
                    let a: Vec<TokenTree> = list.tokens.clone().into_iter().collect();
                    let a = a[index + 2].clone();
                    name = Some(quote! {#a})
                }
                if ident == "query_urls" {
                    let a: Vec<TokenTree> = list.tokens.clone().into_iter().collect();
                    let a = a[index + 2].clone();
                    query = Some(quote! {#a})
                }

                if ident == "msgs_urls" {
                    let a: Vec<TokenTree> = list.tokens.clone().into_iter().collect();
                    let a = a[index + 2].clone();
                    msgs = Some(quote! {#a})
                }
            }
        }
    }

    let query = query.expect("query_urls attribute not found");
    let msgs = msgs.expect("msgs_urls attribute not found");

    let prepath = prepath();

    let expanded = quote! {
        impl #prepath::StargateUrls for #struct_name {

            fn is_query_type_url(&self, type_url: String) -> bool {
                <#query as std::str::FromStr>::from_str(&type_url).is_ok()
            }

            fn is_msg_type_url(&self, type_url: String) -> bool {
                <#msgs as std::str::FromStr>::from_str(&type_url).is_ok()
            }

            fn type_urls(&self) -> Vec<String> {
                let mut urls = Vec::new();
                urls.extend(<#query as #prepath::strum::IntoEnumIterator>::iter().map(|url| url.to_string()));
                urls.extend(<#msgs as #prepath::strum::IntoEnumIterator>::iter().map(|url| url.to_string()));
                urls
            }
        }

        impl #prepath::StargateName for #struct_name {
            fn stargate_name(&self) -> String {
                #name.to_string()
            }
        }
    };

    TokenStream::from(expanded)
}

/// Implements following derive:
///
/// ```ignore
/// // Example
/// #[derive(strum_macros::EnumString, strum_macros::EnumIter, strum_macros::Display)]
/// pub enum Ics20MsgUrls {
///     #[strum(serialize = "/ibc.applications.transfer.v1.MsgTransfer")]
///     MsgTransfer,
///     ... // Others enum fields
/// }
#[proc_macro_attribute]
pub fn urls(_attr: proc_macro::TokenStream, input: proc_macro::TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    let prepath = prepath();

    let expanded = quote! {
        #[derive(
            #prepath::strum_macros::EnumString,
            #prepath::strum_macros::EnumIter,
            #prepath::strum_macros::Display
        )]
        #input
    };
    TokenStream::from(expanded)
}

fn get_attr<'a>(attr_ident: &str, attrs: &'a [syn::Attribute]) -> Option<&'a syn::Attribute> {
    attrs.iter().find(|&attr| {
        attr.path().segments.len() == 1 && attr.path().segments[0].ident == attr_ident
    })
}

#[allow(unreachable_code)]
fn is_internal() -> bool {
    #[cfg(feature = "internal")]
    {
        return true;
    }
    false
}

fn prepath() -> proc_macro2::TokenStream {
    if is_internal() {
        quote! {crate}
    } else {
        quote! {cw_iper_test}
    }
}