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
use std::convert::TryFrom;

use proc_macro2::Ident;
use syn::parse_quote;

use crate::module::{Constructor, Method};

use super::{delegate::Delegate, impl_item::ImplItem};

/// Odra module implementation block.
///
/// # Examples
/// ```
/// # <odra_ir::module::ModuleImpl as TryFrom<syn::ItemImpl>>::try_from(syn::parse_quote! {
/// impl MyModule {
///     #[odra(init)]
///     #[other_attribute]
///     pub fn set_initial_value(&self, value: u32) {
///         // initialization logic goes here
///     }
///
///     pub fn set_value(&self, value: u32) {
///         // logic goes here
///     }
/// }
/// # }).unwrap();
/// ```
pub struct ModuleImpl {
    impl_items: Vec<ImplItem>,
    ident: Ident,
    is_trait_implementation: bool
}

impl ModuleImpl {
    pub fn impl_items(&self) -> &[ImplItem] {
        self.impl_items.as_ref()
    }

    pub fn ident(&self) -> &Ident {
        &self.ident
    }

    pub fn custom_impl_items(&self) -> Vec<&ImplItem> {
        self.impl_items
            .iter()
            .filter(|i| matches!(i, ImplItem::Method(_) | ImplItem::Constructor(_)))
            .collect::<Vec<_>>()
    }

    pub fn get_public_method_iter(&self) -> impl Iterator<Item = &Method> {
        self.impl_items
            .iter()
            .filter_map(|item| match item {
                ImplItem::Method(method) => Some(method),
                _ => None
            })
            .filter(|m| self.is_trait_implementation || m.is_public())
    }

    pub fn get_constructor_iter(&self) -> impl Iterator<Item = &Constructor> {
        self.impl_items.iter().filter_map(|item| match item {
            ImplItem::Constructor(c) => Some(c),
            _ => None
        })
    }

    pub fn public_custom_impl_items(&self) -> Vec<&ImplItem> {
        self.impl_items
            .iter()
            .filter(|item| match item {
                ImplItem::Constructor(_) => true,
                ImplItem::Method(m) => self.is_trait_implementation || m.is_public(),
                ImplItem::Other(_) => false
            })
            .collect::<Vec<_>>()
    }

    pub fn is_trait_implementation(&self) -> bool {
        self.is_trait_implementation
    }
}

impl TryFrom<syn::ItemImpl> for ModuleImpl {
    type Error = syn::Error;

    fn try_from(item_impl: syn::ItemImpl) -> Result<Self, Self::Error> {
        let is_trait_implementation = item_impl.trait_.is_some();
        let path = match &*item_impl.self_ty {
            syn::Type::Path(path) => path,
            _ => todo!()
        };
        let contract_ident = path.path.segments.last().unwrap().clone().ident;

        let delegation_stmts = item_impl
            .items
            .clone()
            .into_iter()
            .filter_map(|item| match item {
                syn::ImplItem::Macro(macro_item) => Some(macro_item),
                _ => None
            })
            .map(|macro_item| syn::parse2::<Delegate>(macro_item.mac.tokens))
            .collect::<Result<Vec<_>, syn::Error>>()?;

        let delegation_stmts = delegation_stmts
            .into_iter()
            .flat_map(|d| d.stmts)
            .collect::<Vec<_>>();

        let delegated_items = delegation_stmts
            .into_iter()
            .flat_map(|stmt| {
                let to = stmt.delegate_to;
                stmt.delegation_block
                    .functions
                    .iter()
                    .map(|func| {
                        let sig = &func.full_sig;
                        let vis = &func.visibility;
                        let ident = &func.ident;
                        let args = &func
                            .args
                            .iter()
                            .map(|ty| ty.pat.clone())
                            .collect::<Vec<_>>();

                        parse_quote!(#vis #sig { #to.#ident(#(#args),*) })
                    })
                    .collect::<Vec<syn::ImplItem>>()
            })
            .map(<ImplItem as TryFrom<_>>::try_from)
            .collect::<Result<Vec<_>, syn::Error>>()?;

        let mut items = item_impl
            .items
            .into_iter()
            .filter(|item| matches!(item, syn::ImplItem::Method(_)))
            .map(<ImplItem as TryFrom<_>>::try_from)
            .collect::<Result<Vec<_>, syn::Error>>()?;

        items.extend(delegated_items);

        Ok(Self {
            impl_items: items,
            ident: contract_ident,
            is_trait_implementation
        })
    }
}

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

    #[test]
    fn impl_items_filtering() {
        let item_impl: syn::ItemImpl = syn::parse_quote! {
            impl Contract {

                #[odra(init)]
                pub fn constructor() {}

                pub(crate) fn crate_public_fn() {}

                pub fn public_fn() {}

                fn private_fn() {}

                delegate! {
                    to self.a {
                        pub fn public_fn_del(&self);
                        pub fn private_fn_del(&self);
                    }
                }
            }
        };
        let module_impl = ModuleImpl::try_from(item_impl).unwrap();

        assert_eq!(module_impl.custom_impl_items().len(), 6);
        assert_eq!(module_impl.public_custom_impl_items().len(), 4);
    }
}