callable.rs 18.1 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
//
// 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.

//! Utilities and helper routines that are useful for both ink! messages
//! and ink! constructors.

use crate::ir;
use core::fmt;
20
21
22
23
use proc_macro2::{
    Ident,
    Span,
};
24
use quote::ToTokens as _;
25
use syn::spanned::Spanned as _;
26
27

/// The kind of externally callable smart contract entity.
28
29
#[derive(Debug, Copy, Clone)]
pub enum CallableKind {
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
    /// An ink! message externally callable.
    Message,
    /// An ink! constructor externally callable.
    Constructor,
}

impl fmt::Display for CallableKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Message => write!(f, "message"),
            Self::Constructor => write!(f, "constructor"),
        }
    }
}

/// Wrapper for a callable that adds its composed selector.
46
#[derive(Debug)]
47
48
49
50
pub struct CallableWithSelector<'a, C> {
    /// The composed selector computed by the associated implementation block
    /// and the given callable.
    composed_selector: ir::Selector,
51
52
    /// The parent implementation block.
    item_impl: &'a ir::ItemImpl,
53
54
55
56
    /// The actual callable.
    callable: &'a C,
}

57
58
59
60
61
62
63
64
65
66
67
impl<C> Copy for CallableWithSelector<'_, C> {}
impl<C> Clone for CallableWithSelector<'_, C> {
    fn clone(&self) -> Self {
        Self {
            composed_selector: self.composed_selector,
            item_impl: self.item_impl,
            callable: self.callable,
        }
    }
}

68
69
70
71
72
impl<'a, C> CallableWithSelector<'a, C>
where
    C: Callable,
{
    /// Creates a new wrapper around the given callable and parent impl block.
73
    pub(super) fn new(item_impl: &'a ir::ItemImpl, callable: &'a C) -> Self {
74
75
        Self {
            composed_selector: compose_selector(item_impl, callable),
76
            item_impl,
77
78
79
80
81
82
83
84
85
86
87
88
            callable,
        }
    }
}

impl<'a, C> CallableWithSelector<'a, C> {
    /// Returns the composed selector of the ink! callable the the impl block.
    pub fn composed_selector(&self) -> ir::Selector {
        self.composed_selector
    }

    /// Returns a shared reference to the underlying callable.
89
    pub fn callable(&self) -> &'a C {
90
91
        self.callable
    }
92
93
94
95
96

    /// Returns the parent implementation block of the ink! callable.
    pub fn item_impl(&self) -> &'a ir::ItemImpl {
        self.item_impl
    }
97
98
99
100
101
102
}

impl<'a, C> Callable for CallableWithSelector<'a, C>
where
    C: Callable,
{
103
    fn kind(&self) -> CallableKind {
104
        <C as Callable>::kind(self.callable)
105
106
    }

107
    fn ident(&self) -> &Ident {
108
        <C as Callable>::ident(self.callable)
109
110
111
    }

    fn user_provided_selector(&self) -> Option<&ir::Selector> {
112
        <C as Callable>::user_provided_selector(self.callable)
113
114
115
    }

    fn is_payable(&self) -> bool {
116
        <C as Callable>::is_payable(self.callable)
117
118
119
    }

    fn visibility(&self) -> Visibility {
120
        <C as Callable>::visibility(self.callable)
121
122
123
    }

    fn inputs(&self) -> InputsIter {
124
        <C as Callable>::inputs(self.callable)
125
126
    }

127
    fn inputs_span(&self) -> Span {
128
        <C as Callable>::inputs_span(self.callable)
129
130
    }

131
    fn statements(&self) -> &[syn::Stmt] {
132
        <C as Callable>::statements(self.callable)
133
134
135
136
137
138
139
    }
}

impl<'a, C> ::core::ops::Deref for CallableWithSelector<'a, C> {
    type Target = C;

    fn deref(&self) -> &Self::Target {
140
        self.callable
141
142
143
144
145
146
147
148
    }
}

/// An ink! callable.
///
/// This is either an ink! message or an ink! constructor.
/// Used to share common behavior between different callable types.
pub trait Callable {
149
150
151
    /// Returns the kind of the ink! callable.
    fn kind(&self) -> CallableKind;

152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
    /// Returns the identifier of the ink! callable.
    fn ident(&self) -> &Ident;

    /// Returns the selector of the ink! callable if any has been manually set.
    fn user_provided_selector(&self) -> Option<&ir::Selector>;

    /// Returns `true` if the ink! callable is flagged as payable.
    ///
    /// # Note
    ///
    /// Flagging as payable is done using the `#[ink(payable)]` attribute.
    fn is_payable(&self) -> bool;

    /// Returns the visibility of the ink! callable.
    fn visibility(&self) -> Visibility;

    /// Returns an iterator yielding all input parameters of the ink! callable.
    fn inputs(&self) -> InputsIter;

171
172
173
    /// Returns the span of the inputs of the ink! callable.
    fn inputs_span(&self) -> Span;

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
237
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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
    /// Returns a slice over shared references to the statements of the callable.
    fn statements(&self) -> &[syn::Stmt];
}

/// Returns the composed selector of the ink! callable.
///
/// Composition takes into account the given [`ir::ItemImpl`].
///
/// # Details
///
/// Given
/// - the callable's identifier `i`
/// - the optionally set callable's selector `s`
/// - the impl blocks trait path in case it implements a trait, `P`
/// - the impl blocks optional user provided namespace `S`
///
/// Then the selector is composed in the following way:
///
/// - If `s` is given we simply return `s`.
/// - Otherwise if `T` is not `None` (trait impl block) we concatenate
///   `S`, `T` and `i` with `::` as separator if `T` refers to a full-path.
///   If `T` refers to a relative path or is just an identifier we only take
///   its last segment `p` (e.g. the trait's identifier) into consideration
///   and use it instead of `P` in the above concatenation.
///   In the following we refer to the resulting concatenation as `C`.
/// - Now we take the BLAKE-2 hash of `C` which results in 32 bytes of output
///   and take the first 4 bytes that are returned in order as the composed
///   selector.
///
/// # Examples
///
/// ## Overriding the composed selector
///
/// Given
///
/// ```no_compile
/// impl MyStorage {
///     #[ink(message, selector = "0xDEADBEEF")]
///     fn my_message(&self) {}
/// }
/// ```
///
/// ... then the selector of `my_message` is simply `0xDEADBEEF` since it overrides
/// the composed selector.
///
/// ## Inherent implementation block
///
/// Given
///
/// ```no_compile
/// impl MyStorage {
///     #[ink(message)]
///     fn my_message(&self) {}
/// }
/// ```
///
/// ... then the selector of `my_message` is composed such as:
/// ```no_compile
/// BLAKE2("my_message".to_string().as_bytes())[0..4]
/// ```
///
/// ## Trait implementation block
///
/// Given
///
/// ```no_compile
/// impl MyTrait for MyStorage {
///     #[ink(message)]
///     fn my_message(&self) {}
/// }
/// ```
///
/// ... then the selector of `my_message` is composed such as:
/// ```no_compile
/// BLAKE2("MyTrait::my_message".to_string().as_bytes())[0..4]
/// ```
///
/// ## Using full path for trait
///
/// Given
///
/// ```no_compile
/// impl ::my_full::long_path::MyTrait for MyStorage {
///     #[ink(message)]
///     fn my_message(&self) {}
/// }
/// ```
///
/// ... then the selector of `my_message` is composed such as:
/// ```no_compile
/// BLAKE2("::my_full::long_path::MyTrait::my_message".to_string().as_bytes())[0..4]
/// ```
///
/// ## Using a namespace
///
/// Given
///
/// ```no_compile
/// #[ink(namespace = "my_namespace")]
/// impl MyTrait for MyStorage {
///     #[ink(message)]
///     fn my_message(&self) {}
/// }
/// ```
///
/// ... then the selector of `my_message` is composed such as:
/// ```no_compile
/// BLAKE2("my_namespace::MyTrait::my_message".to_string().as_bytes())[0..4]
/// ```
///
/// ## Note
///
/// All above examples work similarly for ink! constructors interchangeably.
///
/// ## Usage Recommendations
///
/// These recommendation mainly apply to trait implementation blocks:
///
Michael Müller's avatar
Michael Müller committed
292
/// - The recommendation by the ink! team is to use the full-path approach
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
/// wherever possible; OR import the trait and use only its identifier with
/// an additional namespace if required to disambiguate selectors.
/// - Try not to intermix the above recommendations.
/// - Avoid directly setting the selector of an ink! message or constuctor.
///   Only do this if nothing else helps and you need a very specific selector,
///   e.g. in case of backwards compatibility.
/// - Do not use the namespace unless required to disambiguate.
pub fn compose_selector<C>(item_impl: &ir::ItemImpl, callable: &C) -> ir::Selector
where
    C: Callable,
{
    if let Some(selector) = callable.user_provided_selector() {
        return *selector
    }
    let callable_ident = callable.ident().to_string().into_bytes();
    let namespace_bytes = item_impl
        .namespace()
        .map(|namespace| namespace.as_bytes().to_vec())
        .unwrap_or_default();
    let separator = &b"::"[..];
    let joined = match item_impl.trait_path() {
        None => {
            // Inherent implementation block:
            if namespace_bytes.is_empty() {
                callable_ident
            } else {
                [namespace_bytes, callable_ident].join(separator)
            }
        }
        Some(path) => {
            // Trait implementation block:
            //
            // We need to separate between full-path, e.g. `::my::full::Path`
            // starting with `::` and relative paths for the composition.
            let path_bytes = if path.leading_colon.is_some() {
                let mut str_repr = path.to_token_stream().to_string();
                str_repr.retain(|c| !c.is_whitespace());
                str_repr.into_bytes()
            } else {
                path.segments
                    .last()
                    .expect("encountered empty trait path")
                    .ident
                    .to_string()
                    .into_bytes()
            };
            if namespace_bytes.is_empty() {
                [path_bytes, callable_ident].join(separator)
            } else {
                [namespace_bytes, path_bytes, callable_ident].join(separator)
            }
        }
    };
346
    ir::Selector::new(&joined)
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
}

/// Ensures that common invariants of externally callable ink! entities are met.
///
/// # Errors
///
/// In case any of the common externally callable invariants are not met:
/// - This is `true` if the externally callable is:
///  - generic
///  - const (compile-time evaluatable)
///  - async (async WebAssembly smart contract calling is not allowed)
///  - unsafe (caller provided assertions not yet stable)
/// - Furthermore this is `true` if the externally callable is defined for a
///   non default ABI (e.g. `extern "C"`) or doesn't have valid visibility.
pub(super) fn ensure_callable_invariants(
    method_item: &syn::ImplItemMethod,
    kind: CallableKind,
) -> Result<(), syn::Error> {
365
366
367
368
369
370
371
372
373
    let bad_visibility = match &method_item.vis {
        syn::Visibility::Inherited => None,
        syn::Visibility::Restricted(vis_restricted) => Some(vis_restricted.span()),
        syn::Visibility::Crate(vis_crate) => Some(vis_crate.span()),
        syn::Visibility::Public(_) => None,
    };
    if let Some(bad_visibility) = bad_visibility {
        return Err(format_err!(
            bad_visibility,
374
            "ink! {}s must have public or inherited visibility",
375
            kind
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
        ))
    }
    if !method_item.sig.generics.params.is_empty() {
        return Err(format_err_spanned!(
            method_item.sig.generics.params,
            "ink! {}s must not be generic",
            kind,
        ))
    }
    if method_item.sig.constness.is_some() {
        return Err(format_err_spanned!(
            method_item.sig.constness,
            "ink! {}s must not be const",
            kind,
        ))
    }
    if method_item.sig.asyncness.is_some() {
        return Err(format_err_spanned!(
            method_item.sig.asyncness,
            "ink! {}s must not be async",
            kind,
        ))
    }
    if method_item.sig.unsafety.is_some() {
        return Err(format_err_spanned!(
            method_item.sig.unsafety,
            "ink! {}s must not be unsafe",
            kind,
        ))
    }
    if method_item.sig.abi.is_some() {
        return Err(format_err_spanned!(
            method_item.sig.abi,
            "ink! {}s must have explicit ABI",
            kind,
        ))
    }
    if method_item.sig.variadic.is_some() {
        return Err(format_err_spanned!(
            method_item.sig.variadic,
            "ink! {}s must not be variadic",
            kind,
        ))
    }
    Ok(())
}

/// The visibility of an ink! message or constructor.
#[derive(Debug, Clone)]
pub enum Visibility {
    Public(syn::VisPublic),
    Inherited,
}

impl Visibility {
    /// Returns `true` if the visibility of the ink! message of constructor is public (`pub`).
    ///
    /// # Note
    ///
    /// Messages in normal implementation blocks must have public visibility.
    pub fn is_pub(&self) -> bool {
        matches!(self, Self::Public(_))
    }

    /// Returns `true` if the visibility of the ink! message of constructor is inherited.
    ///
    /// # Note
    ///
    /// Messages in trait implementation blocks must have inherited visibility.
    pub fn is_inherited(&self) -> bool {
        matches!(self, Self::Inherited)
    }
448
449
450
451
452
453
454
455

    /// Returns the associated span if any.
    pub fn span(&self) -> Option<Span> {
        match self {
            Self::Public(vis_public) => Some(vis_public.span()),
            Self::Inherited => None,
        }
    }
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
}

/// Iterator over the input parameters of an ink! message or constructor.
///
/// Does not yield the self receiver of ink! messages.
pub struct InputsIter<'a> {
    iter: syn::punctuated::Iter<'a, syn::FnArg>,
}

impl<'a> From<&'a ir::Message> for InputsIter<'a> {
    fn from(message: &'a ir::Message) -> Self {
        Self {
            iter: message.item.sig.inputs.iter(),
        }
    }
}

impl<'a> From<&'a ir::Constructor> for InputsIter<'a> {
    fn from(constructor: &'a ir::Constructor) -> Self {
        Self {
            iter: constructor.item.sig.inputs.iter(),
        }
    }
}

impl<'a> Iterator for InputsIter<'a> {
    type Item = &'a syn::PatType;

    fn next(&mut self) -> Option<Self::Item> {
        'repeat: loop {
            match self.iter.next() {
                None => return None,
                Some(syn::FnArg::Typed(pat_typed)) => return Some(pat_typed),
                Some(syn::FnArg::Receiver(_)) => continue 'repeat,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::{
        convert::TryFrom,
        fmt::Debug,
    };

    pub enum ExpectedSelector {
        Raw([u8; 4]),
        Blake2(Vec<u8>),
    }

    impl From<[u8; 4]> for ExpectedSelector {
        fn from(raw_selector: [u8; 4]) -> Self {
            ExpectedSelector::Raw(raw_selector)
        }
    }

    impl From<Vec<u8>> for ExpectedSelector {
        fn from(blake2_input: Vec<u8>) -> Self {
            ExpectedSelector::Blake2(blake2_input)
        }
    }

    impl ExpectedSelector {
        pub fn expected_selector(self) -> ir::Selector {
            match self {
523
524
                Self::Raw(raw_selector) => ir::Selector::from_bytes(raw_selector),
                Self::Blake2(blake2_input) => ir::Selector::new(&blake2_input),
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
            }
        }
    }

    /// Asserts that the given ink! implementation block and the given ink!
    /// message result in the same composed selector as the expected bytes.
    fn assert_compose_selector<C, S>(
        item_impl: syn::ItemImpl,
        item_method: syn::ImplItemMethod,
        expected_selector: S,
    ) where
        C: Callable + TryFrom<syn::ImplItemMethod>,
        <C as TryFrom<syn::ImplItemMethod>>::Error: Debug,
        S: Into<ExpectedSelector>,
    {
        assert_eq!(
            compose_selector(
                &<ir::ItemImpl as TryFrom<syn::ItemImpl>>::try_from(item_impl).unwrap(),
                &<C as TryFrom<syn::ImplItemMethod>>::try_from(item_method).unwrap(),
            ),
            expected_selector.into().expected_selector(),
        )
    }

    #[test]
    fn compose_selector_works() {
        assert_compose_selector::<ir::Message, _>(
            syn::parse_quote! {
                #[ink(impl)]
                impl MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            b"my_message".to_vec(),
        );
        assert_compose_selector::<ir::Message, _>(
            syn::parse_quote! {
                #[ink(impl)]
                impl MyTrait for MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            b"MyTrait::my_message".to_vec(),
        );
        assert_compose_selector::<ir::Message, _>(
            syn::parse_quote! {
                #[ink(impl)]
                impl ::my::full::path::MyTrait for MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            b"::my::full::path::MyTrait::my_message".to_vec(),
        );
        assert_compose_selector::<ir::Message, _>(
            syn::parse_quote! {
                #[ink(impl, namespace = "my_namespace")]
                impl MyTrait for MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            b"my_namespace::MyTrait::my_message".to_vec(),
        );
        assert_compose_selector::<ir::Message, _>(
            syn::parse_quote! {
                #[ink(impl)]
                impl MyTrait for MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message, selector = "0xDEADBEEF")]
                fn my_message(&self) {}
            },
            [0xDE, 0xAD, 0xBE, 0xEF],
        );
        assert_compose_selector::<ir::Message, _>(
            syn::parse_quote! {
                #[ink(impl)]
                impl relative::path_to::MyTrait for MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            b"MyTrait::my_message".to_vec(),
        );
    }
}