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
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
292
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
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
448
449
450
451
452
453
454
455
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
523
524
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
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
// Copyright (C) Parity Technologies (UK) Ltd.
//
// 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;
use proc_macro2::{
    Ident,
    Span,
};
use quote::ToTokens as _;
use syn::spanned::Spanned as _;

/// The kind of externally callable smart contract entity.
#[derive(Debug, Copy, Clone)]
pub enum CallableKind {
    /// 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.
#[derive(Debug)]
pub struct CallableWithSelector<'a, C> {
    /// The composed selector computed by the associated implementation block
    /// and the given callable.
    composed_selector: ir::Selector,
    /// The parent implementation block.
    item_impl: &'a ir::ItemImpl,
    /// The actual callable.
    callable: &'a C,
}

impl<C> Copy for CallableWithSelector<'_, C> {}
impl<C> Clone for CallableWithSelector<'_, C> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, C> CallableWithSelector<'a, C>
where
    C: Callable,
{
    /// Creates a new wrapper around the given callable and parent `impl` block.
    pub(super) fn new(item_impl: &'a ir::ItemImpl, callable: &'a C) -> Self {
        Self {
            composed_selector: compose_selector(item_impl, callable),
            item_impl,
            callable,
        }
    }
}

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

    /// Returns a shared reference to the underlying callable.
    pub fn callable(&self) -> &'a C {
        self.callable
    }

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

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

    fn ident(&self) -> &Ident {
        <C as Callable>::ident(self.callable)
    }

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

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

    fn is_default(&self) -> bool {
        <C as Callable>::is_default(self.callable)
    }

    fn has_wildcard_selector(&self) -> bool {
        <C as Callable>::has_wildcard_selector(self.callable)
    }

    fn has_wildcard_complement_selector(&self) -> bool {
        <C as Callable>::has_wildcard_complement_selector(self.callable)
    }

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

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

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

    fn statements(&self) -> &[syn::Stmt] {
        <C as Callable>::statements(self.callable)
    }
}

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

    fn deref(&self) -> &Self::Target {
        self.callable
    }
}

/// 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 {
    /// Returns the kind of the ink! callable.
    fn kind(&self) -> CallableKind;

    /// 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 `true` if the ink! callable is flagged as default.
    ///
    /// # Note
    ///
    /// Flagging as default is done using the `#[ink(default)]` attribute.
    fn is_default(&self) -> bool;

    /// Returns `true` if the ink! callable is flagged as a wildcard selector.
    fn has_wildcard_selector(&self) -> bool;

    /// Returns `true` if the ink! callable is flagged as a wildcard complement selector.
    fn has_wildcard_complement_selector(&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;

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

    /// 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 identifier `i` of the callable
/// - the optionally set selector `s` of the callable
/// - the `impl` blocks trait path in case it implements a trait, `P`
/// - 16 kB 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:
///
/// - The recommendation by the ink! team is to use the full-path approach
/// 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 constructor. 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)
            }
        }
    };
    ir::Selector::compute(&joined)
}

/// 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 evaluable)
///  - `async` (asynchronous 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 does not have valid visibility.
pub(super) fn ensure_callable_invariants(
    method_item: &syn::ImplItemFn,
    kind: CallableKind,
) -> Result<(), syn::Error> {
    let bad_visibility = match &method_item.vis {
        syn::Visibility::Inherited => None,
        syn::Visibility::Restricted(vis_restricted) => Some(vis_restricted.span()),
        syn::Visibility::Public(_) => None,
    };
    if let Some(bad_visibility) = bad_visibility {
        return Err(format_err!(
            bad_visibility,
            "ink! {}s must have public or inherited visibility",
            kind
        ))
    }
    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 not 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,
        ))
    }

    if let Some(arg) = method_item.sig.inputs.iter().find(|input| {
        match input {
            syn::FnArg::Typed(pat) => !matches!(*pat.pat, syn::Pat::Ident(_)),
            _ => false,
        }
    }) {
        return Err(format_err_spanned!(
            arg,
            "ink! {} arguments must have an identifier",
            kind
        ))
    }
    Ok(())
}

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

impl quote::ToTokens for Visibility {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        match self {
            Self::Public(vis_public) => vis_public.to_tokens(tokens),
            Self::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)
    }

    /// 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,
        }
    }
}

/// 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> InputsIter<'a> {
    /// Creates a new inputs iterator over the given `syn` punctuation.
    pub(crate) fn new<P>(inputs: &'a syn::punctuated::Punctuated<syn::FnArg, P>) -> Self {
        Self {
            iter: inputs.iter(),
        }
    }
}

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

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

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,
            }
        }
    }
}

impl<'a> ExactSizeIterator for InputsIter<'a> {
    fn len(&self) -> usize {
        self.iter.len()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use core::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 {
                Self::Raw(raw_selector) => ir::Selector::from(raw_selector),
                Self::Blake2(blake2_input) => ir::Selector::compute(&blake2_input),
            }
        }
    }

    /// 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::ImplItemFn,
        expected_selector: S,
    ) where
        C: Callable + TryFrom<syn::ImplItemFn>,
        <C as TryFrom<syn::ImplItemFn>>::Error: Debug,
        S: Into<ExpectedSelector>,
    {
        assert_eq!(
            compose_selector(
                &<ir::ItemImpl as TryFrom<syn::ItemImpl>>::try_from(item_impl).unwrap(),
                &<C as TryFrom<syn::ImplItemFn>>::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 MyStorage {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            b"my_namespace::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(),
        );
    }
}