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
// This file is part of Gear.

// Copyright (C) 2021-2023 Gear Technologies Inc.
// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0

// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with this program. If not, see <https://www.gnu.org/licenses/>.

//! Provides macros for async runtime of Gear contracts.

use core::fmt::Display;
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::{quote, ToTokens};
use std::collections::BTreeSet;
use syn::{
    parse::{Parse, ParseStream},
    punctuated::Punctuated,
    Path, Token,
};

mod utils;

/// A global flag, determining if `handle_reply` already was generated.
static mut HANDLE_REPLY_FLAG: Flag = Flag(false);

/// A global flag, determining if `handle_signal` already was generated.
static mut HANDLE_SIGNAL_FLAG: Flag = Flag(false);

struct Flag(bool);

impl Flag {
    fn get_and_set(&mut self) -> bool {
        let ret = self.0;
        self.0 = true;
        ret
    }
}

struct MainAttrs {
    handle_reply: Option<Path>,
    handle_signal: Option<Path>,
}

impl MainAttrs {
    fn check_attrs_not_exist(&self) -> Result<(), TokenStream> {
        let Self {
            handle_reply,
            handle_signal,
        } = self;

        for (path, flag) in unsafe {
            [
                (handle_reply, HANDLE_REPLY_FLAG.0),
                (handle_signal, HANDLE_SIGNAL_FLAG.0),
            ]
        } {
            if let (Some(path), true) = (path, flag) {
                return Err(compile_error(path, "parameter already defined"));
            }
        }

        Ok(())
    }
}

impl Parse for MainAttrs {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let punctuated: Punctuated<MainAttr, Token![,]> = Punctuated::parse_terminated(input)?;
        let mut attrs = MainAttrs {
            handle_reply: None,
            handle_signal: None,
        };
        let mut existing_attrs = BTreeSet::new();

        for MainAttr { name, path, .. } in punctuated {
            let name = name.to_string();
            if existing_attrs.contains(&name) {
                return Err(syn::Error::new_spanned(name, "parameter already defined"));
            }

            match &*name {
                "handle_reply" => {
                    attrs.handle_reply = Some(path);
                }
                "handle_signal" => {
                    attrs.handle_signal = Some(path);
                }
                _ => return Err(syn::Error::new_spanned(name, "unknown parameter")),
            }

            existing_attrs.insert(name);
        }

        Ok(attrs)
    }
}

struct MainAttr {
    name: Ident,
    path: Path,
}

impl Parse for MainAttr {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let name: Ident = input.parse()?;
        let _: Token![=] = input.parse()?;
        let path: Path = input.parse()?;

        Ok(Self { name, path })
    }
}

fn compile_error<T: ToTokens, U: Display>(tokens: T, msg: U) -> TokenStream {
    syn::Error::new_spanned(tokens, msg)
        .to_compile_error()
        .into()
}

fn check_signature(name: &str, function: &syn::ItemFn) -> Result<(), TokenStream> {
    if function.sig.ident != name {
        return Err(compile_error(
            &function.sig.ident,
            format!("function must be called `{name}`"),
        ));
    }

    if !function.sig.inputs.is_empty() {
        return Err(compile_error(
            &function.sig.ident,
            "function must have no arguments",
        ));
    }

    if function.sig.asyncness.is_none() {
        return Err(compile_error(
            function.sig.fn_token,
            "function must be async",
        ));
    }

    Ok(())
}

fn generate_handle_reply_if_required(mut code: TokenStream, attr: Option<Path>) -> TokenStream {
    let reply_generated = unsafe { HANDLE_REPLY_FLAG.get_and_set() };
    if !reply_generated {
        let handle_reply: TokenStream = quote!(
            #[no_mangle]
            extern "C" fn handle_reply() {
                gstd::record_reply();
                #attr ();
            }
        )
        .into();
        code.extend([handle_reply]);
    }

    code
}

fn generate_handle_signal_if_required(mut code: TokenStream, attr: Option<Path>) -> TokenStream {
    let signal_generated = unsafe { HANDLE_SIGNAL_FLAG.get_and_set() };
    if !signal_generated {
        let handle_signal: TokenStream = quote!(
            #[no_mangle]
            extern "C" fn handle_signal() {
                gstd::handle_signal();
                #attr ();
            }
        )
        .into();
        code.extend([handle_signal]);
    }

    code
}

fn generate_if_required(code: TokenStream, attrs: MainAttrs) -> TokenStream {
    let code = generate_handle_reply_if_required(code, attrs.handle_reply);
    generate_handle_signal_if_required(code, attrs.handle_signal)
}

/// Mark the main async function to be the program entry point.
///
/// Can be used together with [`macro@async_init`].
///
/// When this macro is used, it’s not possible to specify the `handle` function.
/// If you need to specify the `handle` function explicitly, don't use this macro.
///
/// # Examples
///
/// Simple async handle function:
///
/// ```
/// #[gstd::async_main]
/// async fn main() {
///     gstd::debug!("Hello world!");
/// }
/// # fn main() {}
/// ```
///
/// Use `handle_reply` and `handle_signal` parameters to specify corresponding handlers.
/// Note that custom reply and signal handlers derive their default behavior.
///
/// ```
/// #[gstd::async_main(handle_reply = my_handle_reply)]
/// async fn main() {
///     // ...
/// }
///
/// fn my_handle_reply() {
///     // ...
/// }
/// # fn main() {}
/// ```
#[proc_macro_attribute]
pub fn async_main(attr: TokenStream, item: TokenStream) -> TokenStream {
    let function = syn::parse_macro_input!(item as syn::ItemFn);
    if let Err(tokens) = check_signature("main", &function) {
        return tokens;
    }

    let attrs = syn::parse_macro_input!(attr as MainAttrs);
    if let Err(tokens) = attrs.check_attrs_not_exist() {
        return tokens;
    }

    let body = &function.block;
    let code: TokenStream = quote!(

        fn __main_safe() {
            gstd::message_loop(async #body);
        }

        #[no_mangle]
        extern "C" fn handle() {
            __main_safe();
        }
    )
    .into();

    generate_if_required(code, attrs)
}

/// Mark async function to be the program initialization method.
///
/// Can be used together with [`macro@async_main`].
///
/// The `init` function cannot be specified if this macro is used.
/// If you need to specify the `init` function explicitly, don't use this macro.
///
///
/// # Examples
///
/// Simple async init function:
///
/// ```
/// #[gstd::async_init]
/// async fn init() {
///     gstd::debug!("Hello world!");
/// }
/// ```
///
/// Use `handle_reply` and `handle_signal` parameters to specify corresponding handlers.
/// Note that custom reply and signal handlers derive their default behavior.
///
/// ```
/// #[gstd::async_init(handle_signal = my_handle_signal)]
/// async fn init() {
///     // ...
/// }
///
/// fn my_handle_signal() {
///     // ...
/// }
/// ```
#[proc_macro_attribute]
pub fn async_init(attr: TokenStream, item: TokenStream) -> TokenStream {
    let function = syn::parse_macro_input!(item as syn::ItemFn);
    if let Err(tokens) = check_signature("init", &function) {
        return tokens;
    }

    let attrs = syn::parse_macro_input!(attr as MainAttrs);
    if let Err(tokens) = attrs.check_attrs_not_exist() {
        return tokens;
    }

    let body = &function.block;
    let code: TokenStream = quote!(
        #[no_mangle]
        extern "C" fn init() {
            gstd::message_loop(async #body);
        }
    )
    .into();

    generate_if_required(code, attrs)
}

/// Extends async methods `for_reply` and `for_reply_as` for sending
/// methods.
///
/// # Usage
///
/// ```ignore
/// #[wait_for_reply]
/// pub fn send_bytes<T: AsRef<[u8]>>(program: ActorId, payload: T, value: u128) -> Result<MessageId> {
///   gcore::msg::send(program.into(), payload.as_ref(), value).into_result()
/// }
/// ```
///
/// outputs:
///
/// ```ignore
/// /// Same as [`send_bytes`](self::send_bytes), but the program
/// /// will interrupt until the reply is received.
/// ///
/// /// Argument `reply_deposit: u64` used to provide gas for
/// /// future reply handling (skipped if zero).
/// ///
/// /// # See also
/// ///
/// /// - [`send_bytes_for_reply_as`](self::send_bytes_for_reply_as)
/// pub fn send_bytes_for_reply<T: AsRef<[u8]>>(
///     program: ActorId,
///     payload: T,
///     value: u128,
///     reply_deposit: u64
/// ) -> Result<crate::msg::MessageFuture> {
///     // Function call.
///     let waiting_reply_to = send_bytes(program, payload, value)?;
///
///     // Depositing gas for future reply handling if not zero.
///     if reply_deposit != 0 {
///         crate::exec::reply_deposit(waiting_reply_to, reply_deposit)?;
///     }
///
///     // Registering signal.
///     crate::async_runtime::signals().register_signal(waiting_reply_to);
///
///     Ok(crate::msg::MessageFuture { waiting_reply_to })
/// }
///
/// /// Same as [`send_bytes`](self::send_bytes), but the program
/// /// will interrupt until the reply is received.
/// ///
/// /// Argument `reply_deposit: u64` used to provide gas for
/// /// future reply handling (skipped if zero).
/// ///
/// /// The output should be decodable via SCALE codec.
/// ///
/// /// # See also
/// ///
/// /// - [`send_bytes_for_reply`](self::send_bytes_for_reply)
/// /// - <https://docs.substrate.io/reference/scale-codec>
/// pub fn send_bytes_for_reply_as<T: AsRef<[u8]>, D: crate::codec::Decode>(
///     program: ActorId,
///     payload: T,
///     value: u128,
///     reply_deposit: u64,
/// ) -> Result<crate::msg::CodecMessageFuture<D>> {
///     // Function call.
///     let waiting_reply_to = send_bytes(program, payload, value)?;
///
///     // Depositing gas for future reply handling if not zero.
///     if reply_deposit != 0 {
///         crate::exec::reply_deposit(waiting_reply_to, reply_deposit)?;
///     }
///
///     // Registering signal.
///     crate::async_runtime::signals().register_signal(waiting_reply_to);
///
///     Ok(crate::msg::CodecMessageFuture::<D> {
///         waiting_reply_to,
///         _marker: Default::default(),
///     })
/// }
/// ```
#[proc_macro_attribute]
pub fn wait_for_reply(attr: TokenStream, item: TokenStream) -> TokenStream {
    let function = syn::parse_macro_input!(item as syn::ItemFn);
    let ident = &function.sig.ident;

    // Generate functions' idents.
    let (for_reply, for_reply_as) = (
        utils::with_suffix(ident, "_for_reply"),
        utils::with_suffix(ident, "_for_reply_as"),
    );

    // Generate docs.
    let style = if !attr.is_empty() {
        utils::DocumentationStyle::Method
    } else {
        utils::DocumentationStyle::Function
    };

    let (for_reply_docs, for_reply_as_docs) = utils::wait_for_reply_docs(ident.to_string(), style);

    // Generate arguments.
    let (mut inputs, variadic) = (function.sig.inputs.clone(), function.sig.variadic.clone());
    let args = utils::get_args(&inputs);

    // Add `reply_deposit` argument.
    inputs.push(syn::parse_quote!(reply_deposit: u64));

    // Generate generics.
    let decodable_ty = utils::ident("D");
    let decodable_traits = vec![syn::parse_quote!(crate::codec::Decode)];
    let (for_reply_generics, for_reply_as_generics) = (
        function.sig.generics.clone(),
        utils::append_generic(
            function.sig.generics.clone(),
            decodable_ty,
            decodable_traits,
        ),
    );

    let ident = if !attr.is_empty() {
        assert_eq!(
            attr.to_string(),
            "self",
            "Proc macro attribute should be used only to specify self source of the function"
        );

        quote! { self.#ident }
    } else {
        quote! { #ident }
    };

    quote! {
        #function

        #[doc = #for_reply_docs]
        pub fn #for_reply #for_reply_generics ( #inputs #variadic ) -> Result<crate::msg::MessageFuture> {
            // Function call.
            let waiting_reply_to = #ident #args ?;

            // Depositing gas for future reply handling if not zero.
            if reply_deposit != 0 {
                crate::exec::reply_deposit(waiting_reply_to, reply_deposit)?;
            }

            // Registering signal.
            crate::async_runtime::signals().register_signal(waiting_reply_to);

            Ok(crate::msg::MessageFuture { waiting_reply_to })
        }

        #[doc = #for_reply_as_docs]
        pub fn #for_reply_as #for_reply_as_generics ( #inputs #variadic ) -> Result<crate::msg::CodecMessageFuture<D>> {
            // Function call.
            let waiting_reply_to = #ident #args ?;

            // Depositing gas for future reply handling if not zero.
            if reply_deposit != 0 {
                crate::exec::reply_deposit(waiting_reply_to, reply_deposit)?;
            }

            // Registering signal.
            crate::async_runtime::signals().register_signal(waiting_reply_to);

            Ok(crate::msg::CodecMessageFuture::<D> { waiting_reply_to, _marker: Default::default() })
        }
    }
    .into()
}

/// Similar to [`macro@wait_for_reply`], but works with functions that create programs:
/// It returns a message id with a newly created program id.
#[proc_macro_attribute]
pub fn wait_create_program_for_reply(attr: TokenStream, item: TokenStream) -> TokenStream {
    let function = syn::parse_macro_input!(item as syn::ItemFn);

    let function_ident = &function.sig.ident;

    let ident = if !attr.is_empty() {
        assert_eq!(
            attr.to_string(),
            "Self",
            "Proc macro attribute should be used only to specify Self source of the function"
        );

        quote! { Self::#function_ident }
    } else {
        quote! { #function_ident }
    };

    // Generate functions' idents.
    let (for_reply, for_reply_as) = (
        utils::with_suffix(&function.sig.ident, "_for_reply"),
        utils::with_suffix(&function.sig.ident, "_for_reply_as"),
    );

    // Generate docs.
    let style = if !attr.is_empty() {
        utils::DocumentationStyle::Method
    } else {
        utils::DocumentationStyle::Function
    };

    let (for_reply_docs, for_reply_as_docs) =
        utils::wait_for_reply_docs(function_ident.to_string(), style);

    // Generate arguments.
    let (mut inputs, variadic) = (function.sig.inputs.clone(), function.sig.variadic.clone());
    let args = utils::get_args(&inputs);

    // Add `reply_deposit` argument.
    inputs.push(syn::parse_quote!(reply_deposit: u64));

    // Generate generics.
    let decodable_ty = utils::ident("D");
    let decodable_traits = vec![syn::parse_quote!(crate::codec::Decode)];
    let (for_reply_generics, for_reply_as_generics) = (
        function.sig.generics.clone(),
        utils::append_generic(
            function.sig.generics.clone(),
            decodable_ty,
            decodable_traits,
        ),
    );

    quote! {
        #function

        #[doc = #for_reply_docs]
        pub fn #for_reply #for_reply_generics ( #inputs #variadic ) -> Result<crate::msg::CreateProgramFuture> {
            // Function call.
            let (waiting_reply_to, program_id) = #ident #args ?;

            // Depositing gas for future reply handling if not zero.
            if reply_deposit != 0 {
                crate::exec::reply_deposit(waiting_reply_to, reply_deposit)?;
            }

            // Registering signal.
            crate::async_runtime::signals().register_signal(waiting_reply_to);

            Ok(crate::msg::CreateProgramFuture { waiting_reply_to, program_id })
        }

        #[doc = #for_reply_as_docs]
        pub fn #for_reply_as #for_reply_as_generics ( #inputs #variadic ) -> Result<crate::msg::CodecCreateProgramFuture<D>> {
            // Function call.
            let (waiting_reply_to, program_id) = #ident #args ?;

            // Depositing gas for future reply handling if not zero.
            if reply_deposit != 0 {
                crate::exec::reply_deposit(waiting_reply_to, reply_deposit)?;
            }

            // Registering signal.
            crate::async_runtime::signals().register_signal(waiting_reply_to);

            Ok(crate::msg::CodecCreateProgramFuture::<D> { waiting_reply_to, program_id, _marker: Default::default() })
        }
    }
    .into()
}

#[cfg(test)]
mod tests {
    #[test]
    fn ui() {
        let t = trybuild::TestCases::new();
        t.pass("tests/ui/async_init_works.rs");
        t.pass("tests/ui/async_main_works.rs");
        t.compile_fail("tests/ui/signal_double_definition_not_work.rs");
        t.compile_fail("tests/ui/reply_double_definition_not_work.rs");
    }
}