storage.rs 6.65 KB
Newer Older
1
// Copyright 2018-2021 Parity Technologies (UK) Ltd.
2
3
4
5
6
7
8
9
10
11
12
13
14
//
// 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.

15
16
17
18
use crate::{
    ir,
    ir::utils,
};
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
use core::convert::TryFrom;
use proc_macro2::Ident;
use syn::spanned::Spanned as _;

/// An ink! storage struct definition.
///
/// Noticed by ink! through the `#[ink(storage)]` annotation.
///
/// # Note
///
/// An ink! smart contract must have exactly one storage definition.
/// The storage definition must be found in the root of the ink! module.
///
/// # Example
///
/// ```
/// # use core::convert::TryFrom;
/// # <ink_lang_ir::Storage as TryFrom<syn::ItemStruct>>::try_from(syn::parse_quote! {
/// #[ink(storage)]
/// pub struct MyStorage {
///     my_value: bool,
///      counter: u32,
/// }
/// # }).unwrap();
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct Storage {
    /// The underlying `struct` Rust item.
    ast: syn::ItemStruct,
}

impl quote::ToTokens for Storage {
    /// We mainly implement this trait for this ink! type to have a derived
    /// [`Spanned`](`syn::spanned::Spanned`) implementation for it.
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        self.ast.to_tokens(tokens)
    }
}

impl Storage {
    /// Returns `true` if the first ink! annotation on the given struct is
    /// `#[ink(storage)]`.
    ///
    /// # Errors
    ///
    /// If the first found ink! attribute is malformed.
    pub(super) fn is_ink_storage(
        item_struct: &syn::ItemStruct,
    ) -> Result<bool, syn::Error> {
        if !ir::contains_ink_attributes(&item_struct.attrs) {
            return Ok(false)
        }
        // At this point we know that there must be at least one ink!
        // attribute. This can be either the ink! storage struct,
        // an ink! event or an invalid ink! attribute.
        let attr = ir::first_ink_attribute(&item_struct.attrs)?
            .expect("missing expected ink! attribute for struct");
76
        Ok(matches!(attr.first().kind(), ir::AttributeArg::Storage))
77
78
79
80
81
82
83
84
85
86
87
88
    }
}

impl TryFrom<syn::ItemStruct> for Storage {
    type Error = syn::Error;

    fn try_from(item_struct: syn::ItemStruct) -> Result<Self, Self::Error> {
        let struct_span = item_struct.span();
        let (_ink_attrs, other_attrs) = ir::sanitize_attributes(
            struct_span,
            item_struct.attrs,
            &ir::AttributeArgKind::Storage,
89
90
91
92
93
94
            |arg| {
                match arg.kind() {
                    ir::AttributeArg::Storage => Ok(()),
                    _ => Err(None),
                }
            },
95
96
97
98
99
100
101
        )?;
        if !item_struct.generics.params.is_empty() {
            return Err(format_err_spanned!(
                item_struct.generics.params,
                "generic ink! storage structs are not supported",
            ))
        }
102
        utils::ensure_pub_visibility("storage structs", struct_span, &item_struct.vis)?;
103
104
105
106
107
108
109
110
111
112
        Ok(Self {
            ast: syn::ItemStruct {
                attrs: other_attrs,
                ..item_struct
            },
        })
    }
}

impl Storage {
113
114
115
116
117
    /// Returns the non-ink! attributes of the ink! storage struct.
    pub fn attrs(&self) -> &[syn::Attribute] {
        &self.ast.attrs
    }

118
119
120
121
122
    /// Returns the identifier of the storage struct.
    pub fn ident(&self) -> &Ident {
        &self.ast.ident
    }

123
    /// Returns an iterator yielding all fields of the storage struct.
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
    pub fn fields(&self) -> syn::punctuated::Iter<syn::Field> {
        self.ast.fields.iter()
    }
}

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

    #[test]
    fn simple_try_from_works() {
        let item_struct: syn::ItemStruct = syn::parse_quote! {
            #[ink(storage)]
            pub struct MyStorage {
                field_1: i32,
                field_2: bool,
            }
        };
        assert!(Storage::try_from(item_struct).is_ok())
    }

    fn assert_try_from_fails(item_struct: syn::ItemStruct, expected: &str) {
        assert_eq!(
            Storage::try_from(item_struct).map_err(|err| err.to_string()),
            Err(expected.to_string())
        )
    }

    #[test]
    fn conflicting_attributes_fails() {
        assert_try_from_fails(
            syn::parse_quote! {
                #[ink(storage)]
                #[ink(event)]
                pub struct MyStorage {
                    field_1: i32,
                    field_2: bool,
                }
            },
            "encountered conflicting ink! attribute argument",
        )
    }

    #[test]
    fn duplicate_attributes_fails() {
        assert_try_from_fails(
            syn::parse_quote! {
                #[ink(storage)]
                #[ink(storage)]
                pub struct MyStorage {
                    field_1: i32,
                    field_2: bool,
                }
            },
            "encountered duplicate ink! attribute",
        )
    }

    #[test]
    fn wrong_first_attribute_fails() {
        assert_try_from_fails(
            syn::parse_quote! {
                #[ink(event)]
                #[ink(storage)]
                pub struct MyStorage {
                    field_1: i32,
                    field_2: bool,
                }
            },
            "unexpected first ink! attribute argument",
        )
    }

    #[test]
    fn missing_storage_attribute_fails() {
        assert_try_from_fails(
            syn::parse_quote! {
                pub struct MyStorage {
                    field_1: i32,
                    field_2: bool,
                }
            },
            "encountered unexpected empty expanded ink! attribute arguments",
        )
    }

    #[test]
    fn generic_storage_fails() {
        assert_try_from_fails(
            syn::parse_quote! {
                #[ink(storage)]
                pub struct GenericStorage<T> {
                    field_1: T,
                }
            },
            "generic ink! storage structs are not supported",
        )
    }

    #[test]
    fn non_pub_storage_struct() {
        assert_try_from_fails(
            syn::parse_quote! {
                #[ink(storage)]
                struct PrivateStorage {
                    field_1: i32,
                    field_2: bool,
                }
            },
            "non `pub` ink! storage structs are not supported",
        )
    }
}