message.rs 22.5 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
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
//
// 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.

use super::{
    ensure_callable_invariants,
    Callable,
    CallableKind,
    InputsIter,
    Visibility,
};
use crate::ir;
use core::convert::TryFrom;
use proc_macro2::{
    Ident,
    Span,
};
use syn::spanned::Spanned as _;

/// The receiver of an ink! message.
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum Receiver {
    /// The `&self` message receiver.
    Ref,
    /// The `&mut self` message receiver.
    RefMut,
}

39
40
41
42
43
44
45
46
47
48
impl quote::ToTokens for Receiver {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        let receiver = match self {
            Self::Ref => quote::quote! { &self },
            Self::RefMut => quote::quote! { &mut self },
        };
        tokens.extend(receiver);
    }
}

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
impl Receiver {
    /// Returns `true` if the receiver is `&self`.
    pub fn is_ref(self) -> bool {
        matches!(self, Self::Ref)
    }

    /// Returns `true` if the receiver is `&mut self`.
    pub fn is_ref_mut(self) -> bool {
        matches!(self, Self::RefMut)
    }
}

/// An ink! message definition.
///
/// # Example
///
/// ## Inherent implementation message:
///
/// ```
/// # use core::convert::TryFrom;
/// # <ink_lang_ir::ItemImpl as TryFrom<syn::ItemImpl>>::try_from(syn::parse_quote! {
/// impl MyStorage {
///     #[ink(message)]
///     pub fn my_message(&self, input: i32) -> bool {
///         /* message implementation goes here */
/// #       unimplemented!()
///     }
/// }
/// # }).unwrap();
/// ```
///
/// ## Trait implementation message:
///
/// ```
/// # use core::convert::TryFrom;
/// # let event = <ink_lang_ir::ItemImpl as TryFrom<syn::ItemImpl>>::try_from(syn::parse_quote! {
/// impl MyTrait for MyStorage {
///     #[ink(message)]
///     fn my_message(&mut self, input: bool) -> i32 {
///         /* message implementation goes here */
/// #       unimplemented!()
///     }
/// }
/// # }).unwrap();
/// ```
#[derive(Debug, PartialEq, Eq)]
pub struct Message {
    /// The underlying Rust method item.
    pub(super) item: syn::ImplItemMethod,
    /// If the ink! message can receive funds.
    is_payable: bool,
    /// An optional user provided selector.
    ///
    /// # Note
    ///
    /// This overrides the computed selector, even when using a manual namespace
    /// for the parent implementation block.
    selector: Option<ir::Selector>,
}

impl quote::ToTokens for Message {
    /// 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.item.to_tokens(tokens)
    }
}

impl Message {
    /// Ensures that the given method inputs start with `&self` or `&mut self`
    /// receivers.
    ///
    /// If not an appropriate error is returned.
    ///
    /// # Errors
    ///
    /// - If the method inputs yields no elements.
    /// - If the first method input is not `&self` or `&mut self`.
    fn ensure_receiver_is_self_ref(
        method_item: &syn::ImplItemMethod,
    ) -> Result<(), syn::Error> {
        let mut fn_args = method_item.sig.inputs.iter();
        fn bail(span: Span) -> syn::Error {
            format_err!(
                span,
                "ink! messages must have `&self` or `&mut self` receiver",
            )
        }
        match fn_args.next() {
            None => return Err(bail(method_item.span())),
            Some(syn::FnArg::Typed(pat_typed)) => return Err(bail(pat_typed.span())),
            Some(syn::FnArg::Receiver(receiver)) => {
                if receiver.reference.is_none() {
                    return Err(bail(receiver.span()))
                }
            }
        }
        Ok(())
    }

149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
    /// Ensures that the ink! message does not return `Self`.
    ///
    /// # Errors
    ///
    /// If the given Rust method has a `Self` return type.
    fn ensure_not_return_self(
        method_item: &syn::ImplItemMethod,
    ) -> Result<(), syn::Error> {
        match &method_item.sig.output {
            syn::ReturnType::Default => (),
            syn::ReturnType::Type(_arrow, ret_type) => {
                if let syn::Type::Path(type_path) = &**ret_type {
                    if type_path.path.is_ident("Self") {
                        return Err(format_err!(
                            ret_type,
                            "ink! messages must not return `Self`"
                        ))
                    }
                }
            }
        }
        Ok(())
    }

173
174
175
176
177
178
179
180
181
182
    /// Sanitizes the attributes for the ink! message.
    ///
    /// Returns a tuple of ink! attributes and non-ink! attributes.
    fn sanitize_attributes(
        method_item: &syn::ImplItemMethod,
    ) -> Result<(ir::InkAttribute, Vec<syn::Attribute>), syn::Error> {
        ir::sanitize_attributes(
            method_item.span(),
            method_item.attrs.clone(),
            &ir::AttributeArgKind::Message,
183
184
            |arg| {
                match arg.kind() {
185
                    ir::AttributeArg::Message
186
187
188
189
                    | ir::AttributeArg::Payable
                    | ir::AttributeArg::Selector(_) => Ok(()),
                    _ => Err(None),
                }
190
191
192
193
194
195
196
197
198
199
200
            },
        )
    }
}

impl TryFrom<syn::ImplItemMethod> for Message {
    type Error = syn::Error;

    fn try_from(method_item: syn::ImplItemMethod) -> Result<Self, Self::Error> {
        ensure_callable_invariants(&method_item, CallableKind::Message)?;
        Self::ensure_receiver_is_self_ref(&method_item)?;
201
        Self::ensure_not_return_self(&method_item)?;
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
        let (ink_attrs, other_attrs) = Self::sanitize_attributes(&method_item)?;
        let is_payable = ink_attrs.is_payable();
        let selector = ink_attrs.selector();
        Ok(Self {
            is_payable,
            selector,
            item: syn::ImplItemMethod {
                attrs: other_attrs,
                ..method_item
            },
        })
    }
}

impl Callable for Message {
217
218
219
220
    fn kind(&self) -> CallableKind {
        CallableKind::Message
    }

221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
    fn ident(&self) -> &Ident {
        &self.item.sig.ident
    }

    fn user_provided_selector(&self) -> Option<&ir::Selector> {
        self.selector.as_ref()
    }

    fn is_payable(&self) -> bool {
        self.is_payable
    }

    fn visibility(&self) -> Visibility {
        match &self.item.vis {
            syn::Visibility::Public(vis_public) => Visibility::Public(vis_public.clone()),
            syn::Visibility::Inherited => Visibility::Inherited,
            _ => unreachable!("encountered invalid visibility for ink! message"),
        }
    }

    fn inputs(&self) -> InputsIter {
        InputsIter::from(self)
    }

245
246
247
248
    fn inputs_span(&self) -> Span {
        self.item.sig.inputs.span()
    }

249
250
251
252
253
254
    fn statements(&self) -> &[syn::Stmt] {
        &self.item.block.stmts
    }
}

impl Message {
255
256
257
258
259
    /// Returns a slice of all non-ink! attributes of the ink! message.
    pub fn attrs(&self) -> &[syn::Attribute] {
        &self.item.attrs
    }

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
    /// Returns the `self` receiver of the ink! message.
    pub fn receiver(&self) -> Receiver {
        match self.item.sig.inputs.iter().next() {
            Some(syn::FnArg::Receiver(receiver)) => {
                debug_assert!(receiver.reference.is_some());
                if receiver.mutability.is_some() {
                    Receiver::RefMut
                } else {
                    Receiver::Ref
                }
            }
            _ => unreachable!("encountered invalid receiver argument for ink! message"),
        }
    }

    /// Returns the return type of the ink! message if any.
    pub fn output(&self) -> Option<&syn::Type> {
        match &self.item.sig.output {
            syn::ReturnType::Default => None,
            syn::ReturnType::Type(_, return_type) => Some(return_type),
        }
    }
}

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

    #[test]
    fn output_works() {
        let test_inputs: Vec<(Option<syn::Type>, syn::ImplItemMethod)> = vec![
            (
                // No output:
                None,
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) {}
                },
            ),
            (
                // Single output:
                Some(syn::parse_quote! { i32 }),
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) -> i32 {}
                },
            ),
            (
                // Tuple output:
                Some(syn::parse_quote! { (i32, u64, bool) }),
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) -> (i32, u64, bool) {}
                },
            ),
        ];
        for (expected_output, item_method) in test_inputs {
            let actual_output = <ir::Message as TryFrom<_>>::try_from(item_method)
                .unwrap()
                .output()
                .cloned();
            assert_eq!(actual_output, expected_output);
        }
    }

    #[test]
    fn inputs_works() {
        macro_rules! expected_inputs {
            ( $( $name:ident: $ty:ty ),* ) => {{
                vec![
                    $(
                        syn::parse_quote! {
                            $name: $ty
                        }
                    ),*
                ]
            }};
        }
        let test_inputs: Vec<(Vec<syn::FnArg>, syn::ImplItemMethod)> = vec![
            (
                // No inputs:
                expected_inputs!(),
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) {}
                },
            ),
            (
                // Single input:
                expected_inputs!(a: i32),
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self, a: i32) {}
                },
            ),
            (
                // Some inputs:
                expected_inputs!(a: i32, b: u64, c: [u8; 32]),
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self, a: i32, b: u64, c: [u8; 32]) {}
                },
            ),
        ];
        for (expected_inputs, item_method) in test_inputs {
            let actual_inputs = <ir::Message as TryFrom<_>>::try_from(item_method)
                .unwrap()
                .inputs()
                .cloned()
369
                .map(syn::FnArg::Typed)
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
                .collect::<Vec<_>>();
            assert_eq!(actual_inputs, expected_inputs);
        }
    }

    #[test]
    fn is_payable_works() {
        let test_inputs: Vec<(bool, syn::ImplItemMethod)> = vec![
            // Not payable.
            (
                false,
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) {}
                },
            ),
            // Normalized ink! attribute.
            (
                true,
                syn::parse_quote! {
                    #[ink(message, payable)]
                    pub fn my_message(&self) {}
                },
            ),
            // Different ink! attributes.
            (
                true,
                syn::parse_quote! {
                    #[ink(message)]
                    #[ink(payable)]
                    pub fn my_message(&self) {}
                },
            ),
            // Another ink! attribute, separate and normalized attribute.
            (
                true,
                syn::parse_quote! {
                    #[ink(message)]
408
                    #[ink(selector = 0xDEADBEEF, payable)]
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
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
                    pub fn my_message(&self) {}
                },
            ),
        ];
        for (expect_payable, item_method) in test_inputs {
            let is_payable = <ir::Message as TryFrom<_>>::try_from(item_method)
                .unwrap()
                .is_payable();
            assert_eq!(is_payable, expect_payable);
        }
    }

    #[test]
    fn receiver_works() {
        let test_inputs: Vec<(Receiver, syn::ImplItemMethod)> = vec![
            (
                Receiver::Ref,
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) {}
                },
            ),
            (
                Receiver::RefMut,
                syn::parse_quote! {
                    #[ink(message, payable)]
                    fn my_message(&mut self) {}
                },
            ),
        ];
        for (expected_receiver, item_method) in test_inputs {
            let actual_receiver = <ir::Message as TryFrom<_>>::try_from(item_method)
                .unwrap()
                .receiver();
            assert_eq!(actual_receiver, expected_receiver);
        }
    }

    #[test]
    fn visibility_works() {
        let test_inputs: Vec<(bool, syn::ImplItemMethod)> = vec![
            // &self
            (
                false,
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&self) {}
                },
            ),
            // &self + pub
            (
                true,
                syn::parse_quote! {
                    #[ink(message)]
                    pub fn my_message(&self) {}
                },
            ),
            // &mut self
            (
                false,
                syn::parse_quote! {
                    #[ink(message)]
                    fn my_message(&mut self) {}
                },
            ),
            // &mut self + pub
            (
                true,
                syn::parse_quote! {
                    #[ink(message)]
                    pub fn my_message(&mut self) {}
                },
            ),
        ];
        for (is_pub, item_method) in test_inputs {
            let visibility = <ir::Message as TryFrom<_>>::try_from(item_method)
                .unwrap()
                .visibility();
            assert_eq!(visibility.is_pub(), is_pub);
            assert_eq!(visibility.is_inherited(), !is_pub);
        }
    }

    #[test]
    fn try_from_works() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self) {}
            },
            // &self + pub
            syn::parse_quote! {
                #[ink(message)]
                pub fn my_message(&self) {}
            },
            // &mut self
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&mut self) {}
            },
            // &mut self + pub
            syn::parse_quote! {
                #[ink(message)]
                pub fn my_message(&mut self) {}
            },
            // &self + payable
            syn::parse_quote! {
                #[ink(message, payable)]
                fn my_message(&self) {}
            },
            // &mut self + payable
            syn::parse_quote! {
                #[ink(message, payable)]
                fn my_message(&mut self) {}
            },
            // &self + many inputs + output works
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self, input1: i32, input2: i64, input3: u32, input4: u64) -> bool {}
            },
            // &mut self + many inputs + output works
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&mut self, input1: i32, input2: i64, input3: u32, input4: u64) -> bool {}
            },
        ];
        for item_method in item_methods {
            assert!(<ir::Message as TryFrom<_>>::try_from(item_method).is_ok());
        }
    }

    fn assert_try_from_fails(item_method: syn::ImplItemMethod, expected_err: &str) {
        assert_eq!(
            <ir::Message as TryFrom<_>>::try_from(item_method)
                .map_err(|err| err.to_string()),
            Err(expected_err.to_string()),
        );
    }

    #[test]
    fn try_from_generics_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            syn::parse_quote! {
                #[ink(message)]
                fn my_message<T>(&self) {}
            },
            syn::parse_quote! {
                #[ink(message)]
                pub fn my_message<T>(&self) {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message<T>(&mut self) {}
            },
            syn::parse_quote! {
                #[ink(message)]
                pub fn my_message<T>(&mut self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(item_method, "ink! messages must not be generic")
        }
    }

    #[test]
    fn try_from_receiver_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            syn::parse_quote! {
                #[ink(message)]
                fn my_message() {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(self) {}
            },
            syn::parse_quote! {
                #[ink(message)]
                pub fn my_message(mut self) {}
            },
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(this: &Self) {}
            },
            syn::parse_quote! {
                #[ink(message)]
                pub fn my_message(this: &mut Self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(
                item_method,
                "ink! messages must have `&self` or `&mut self` receiver",
            )
        }
    }

    #[test]
    fn try_from_const_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self
            syn::parse_quote! {
                #[ink(message)]
                const fn my_message(&self) {}
            },
            // &mut self
            syn::parse_quote! {
                #[ink(message)]
                const fn my_message(&mut self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(item_method, "ink! messages must not be const")
        }
    }

    #[test]
    fn try_from_async_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self
            syn::parse_quote! {
                #[ink(message)]
                async fn my_message(&self) {}
            },
            // &mut self
            syn::parse_quote! {
                #[ink(message)]
                async fn my_message(&mut self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(item_method, "ink! messages must not be async")
        }
    }

    #[test]
    fn try_from_unsafe_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self
            syn::parse_quote! {
                #[ink(message)]
                unsafe fn my_message(&self) {}
            },
            // &mut self
            syn::parse_quote! {
                #[ink(message)]
                unsafe fn my_message(&mut self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(item_method, "ink! messages must not be unsafe")
        }
    }

    #[test]
    fn try_from_explicit_abi_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self
            syn::parse_quote! {
                #[ink(message)]
                extern "C" fn my_message(&self) {}
            },
            // &mut self
            syn::parse_quote! {
                #[ink(message)]
                extern "C" fn my_message(&mut self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(item_method, "ink! messages must have explicit ABI")
        }
    }

    #[test]
    fn try_from_variadic_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&self, ...) {}
            },
            // &mut self
            syn::parse_quote! {
                #[ink(message)]
                fn my_message(&mut self, ...) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(item_method, "ink! messages must not be variadic")
        }
    }

    #[test]
    fn try_from_visibility_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // &self + crate visibility
            syn::parse_quote! {
                #[ink(message)]
                crate fn my_message(&self) {}
            },
            // &mut self + crate visibility
            syn::parse_quote! {
                #[ink(message)]
                crate fn my_message(&mut self) {}
            },
            // &self + pub restricted visibility
            syn::parse_quote! {
                #[ink(message)]
                pub(in my::path) fn my_message(&self) {}
            },
            // &mut self + pub restricted visibility
            syn::parse_quote! {
                #[ink(message)]
                pub(in my::path) fn my_message(&mut self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(
                item_method,
                "ink! messages must have public or inherited visibility",
            )
        }
    }

    #[test]
    fn conflicting_attributes_fails() {
        let item_methods: Vec<syn::ImplItemMethod> = vec![
            // storage
            syn::parse_quote! {
                #[ink(message, storage)]
                fn my_message(&self) {}
            },
            // namespace
            syn::parse_quote! {
                #[ink(message, namespace = "my_namespace")]
                fn my_message(&self) {}
            },
            // event + multiple attributes
            syn::parse_quote! {
                #[ink(message)]
                #[ink(event)]
                fn my_message(&self) {}
            },
        ];
        for item_method in item_methods {
            assert_try_from_fails(
                item_method,
                "encountered conflicting ink! attribute argument",
            )
        }
    }
}