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
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
761
762
763
764
765
766
767
768
769
770
771
772
773
#![doc(
    html_logo_url = "https://github.com/cncf/artwork/blob/master/projects/wasm-edge-runtime/icon/color/wasm-edge-runtime-icon-color.png?raw=true",
    html_favicon_url = "https://raw.githubusercontent.com/cncf/artwork/49169bdbc88a7ce3c4a722c641cc2d548bd5c340/projects/wasm-edge-runtime/icon/color/wasm-edge-runtime-icon-color.svg"
)]

//! # Overview
//! The [wasmedge-macro](https://crates.io/crates/wasmedge-macro) crate defines a group of procedural macros used by both [wasmedge-sdk](https://crates.io/crates/wasmedge-sdk) and [wasmedge-sys](https://crates.io/crates/wasmedge-sys) crates.

use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, spanned::Spanned, FnArg, Item, Pat, PatType};

// ================== macros for wasmedge-sdk ==================

/// Declare a native function that will be used to create a host function instance.
#[proc_macro_attribute]
pub fn host_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let body_ast = parse_macro_input!(item as Item);
    if let Item::Fn(item_fn) = body_ast {
        match expand_host_func(&item_fn) {
            Ok(token_stream) => token_stream.into(),
            Err(err) => err.to_compile_error().into(),
        }
    } else {
        TokenStream::new()
    }
}

fn expand_host_func(item_fn: &syn::ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    // extract T from Option<&mut T>
    let ret = match &item_fn.sig.inputs.len() {
        2 => expand_host_func_with_two_args(item_fn),
        3 => expand_host_func_with_three_args(item_fn),
        _ => panic!(
            "Invalid numbers of host function arguments: {}",
            &item_fn.sig.inputs.len()
        ),
    };

    Ok(ret)
}

fn expand_host_func_with_two_args(item_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    // * define the signature of wrapper function
    // name of wrapper function
    let wrapper_fn_name_ident = item_fn.sig.ident.clone();
    let wrapper_fn_name_literal = wrapper_fn_name_ident.to_string();
    // arguments of wrapper function
    let wrapper_fn_inputs: syn::punctuated::Punctuated<FnArg, syn::token::Comma> = parse_quote!(
        frame: wasmedge_sdk::CallingFrame,
        args: Vec<wasmedge_sdk::WasmValue>,
        _data: *mut std::os::raw::c_void
    );
    // return type of wrapper function
    let wrapper_fn_return = item_fn.sig.output.clone();
    // visibility of wrapper function
    let wrapper_visibility = item_fn.vis.clone();

    // get the name of the first argument
    let (ident_first_arg, mutability) = match &item_fn.sig.inputs[0] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => (pat_ident.ident.clone(), pat_ident.mutability),
            Pat::Wild(_) => (
                proc_macro2::Ident::new("_caller", proc_macro2::Span::call_site()),
                None,
            ),
            _ => panic!("The argument pattern of the first argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The first argument is a receiver"),
    };

    // get the name of the second argument
    let ident_second_arg = match &item_fn.sig.inputs[1] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => pat_ident.ident.clone(),
            Pat::Wild(_) => proc_macro2::Ident::new("_args", proc_macro2::Span::call_site()),
            _ => panic!("The argument pattern of the second argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The second argument is a receiver"),
    };

    // * define the signature of inner function
    // name of inner function
    let inner_fn_name_literal = format!("inner_{wrapper_fn_name_literal}");
    let inner_fn_name_ident = syn::Ident::new(&inner_fn_name_literal, item_fn.sig.span());
    // arguments of inner function
    let inner_fn_inputs = item_fn.sig.inputs.clone();
    // return type of inner function
    let inner_fn_return = item_fn.sig.output.clone();
    // body of inner function
    let inner_fn_block = item_fn.block.clone();

    quote!(
        # wrapper_visibility fn #wrapper_fn_name_ident (#wrapper_fn_inputs) #wrapper_fn_return {
            // define inner function
            fn #inner_fn_name_ident (#inner_fn_inputs) #inner_fn_return {
                #inner_fn_block
            }

            // create a Caller instance
            let #mutability #ident_first_arg = Caller::new(frame);

            let #ident_second_arg = args;

            #inner_fn_name_ident(#ident_first_arg, #ident_second_arg)
        }
    )
}

fn expand_host_func_with_three_args(item_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    // * define the signature of wrapper function
    // name of wrapper function
    let wrapper_fn_name_ident = item_fn.sig.ident.clone();
    let wrapper_fn_name_literal = wrapper_fn_name_ident.to_string();
    // arguments of wrapper function
    let wrapper_fn_inputs: syn::punctuated::Punctuated<FnArg, syn::token::Comma> = parse_quote!(
        frame: wasmedge_sdk::CallingFrame,
        args: Vec<wasmedge_sdk::WasmValue>,
        data: *mut std::os::raw::c_void
    );
    // return type of wrapper function
    let wrapper_fn_return = item_fn.sig.output.clone();
    // visibility of wrapper function
    let wrapper_visibility = item_fn.vis.clone();

    // * define the signature of inner function
    // name of inner function
    let inner_fn_name_literal = format!("inner_{wrapper_fn_name_literal}");
    let inner_fn_name_ident = syn::Ident::new(&inner_fn_name_literal, item_fn.sig.span());
    // arguments of inner function
    let inner_fn_inputs = item_fn.sig.inputs.clone();
    // return type of inner function
    let inner_fn_return = item_fn.sig.output.clone();
    // body of inner function
    let inner_fn_block = item_fn.block.clone();

    // extract T from Option<&mut T>

    let data_arg = item_fn.sig.inputs.last().unwrap().clone();
    let ty_ptr = match &data_arg {
        FnArg::Typed(PatType { ref ty, .. }) => match **ty {
            syn::Type::Reference(syn::TypeReference { ref elem, .. }) => syn::TypePtr {
                star_token: parse_quote!(*),
                const_token: None,
                mutability: Some(parse_quote!(mut)),
                elem: elem.clone(),
            },
            syn::Type::Path(syn::TypePath { ref path, .. }) => match path.segments.last() {
                Some(segment) => {
                    let id = segment.ident.to_string();
                    match id == "Option" {
                        true => match segment.arguments {
                            syn::PathArguments::AngleBracketed(
                                syn::AngleBracketedGenericArguments { ref args, .. },
                            ) => {
                                let last_generic_arg = args.last();
                                match last_generic_arg {
                                    Some(arg) => match arg {
                                        syn::GenericArgument::Type(ty) => match ty {
                                            syn::Type::Reference(syn::TypeReference {
                                                ref elem,
                                                ..
                                            }) => syn::TypePtr {
                                                star_token: parse_quote!(*),
                                                const_token: None,
                                                mutability: Some(parse_quote!(mut)),
                                                elem: elem.clone(),
                                            },
                                            _ => panic!("Not found syn::Type::Reference"),
                                        },
                                        _ => {
                                            panic!("Not found syn::GenericArgument::Type")
                                        }
                                    },
                                    None => panic!("Not found the last GenericArgument"),
                                }
                            }
                            _ => panic!("Not found syn::PathArguments::AngleBracketed"),
                        },
                        false => panic!("Not found segment ident: Option"),
                    }
                }
                None => panic!("Not found path segments"),
            },
            _ => panic!("Unsupported syn::Type type"),
        },
        _ => panic!("Unsupported syn::FnArg type"),
    };

    // generate token stream
    quote!(
        # wrapper_visibility fn #wrapper_fn_name_ident (#wrapper_fn_inputs) #wrapper_fn_return {
            // define inner function
            fn #inner_fn_name_ident (#inner_fn_inputs) #inner_fn_return {
                #inner_fn_block
            }

            // create a Caller instance
            let caller = Caller::new(frame);

            let data = unsafe { &mut *(data as #ty_ptr) };

            #inner_fn_name_ident(caller, args, data)
        }
    )
}

/// Declare a native async function that will be used to create an async host function instance.
#[proc_macro_attribute]
pub fn async_host_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let body_ast = parse_macro_input!(item as Item);
    if let Item::Fn(item_fn) = body_ast {
        if item_fn.sig.asyncness.is_none() {
            panic!("The function must be async");
        }

        match expand_async_host_func(&item_fn) {
            Ok(token_stream) => token_stream.into(),
            Err(err) => err.to_compile_error().into(),
        }
    } else {
        TokenStream::new()
    }
}

fn expand_async_host_func(item_fn: &syn::ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    // extract T from Option<&mut T>
    let ret = match &item_fn.sig.inputs.len() {
        2 => expand_async_host_func_with_two_args(item_fn),
        3 => expand_async_host_func_with_three_args(item_fn),
        _ => panic!(
            "Invalid numbers of host function arguments: {}",
            &item_fn.sig.inputs.len()
        ),
    };

    Ok(ret)
}

fn expand_async_host_func_with_two_args(item_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    // * define the signature of wrapper function
    // name of wrapper function
    let wrapper_fn_name_ident = item_fn.sig.ident.clone();
    // arguments of wrapper function
    let wrapper_fn_inputs: syn::punctuated::Punctuated<FnArg, syn::token::Comma> = parse_quote!(
        frame: wasmedge_sdk::CallingFrame,
        args: Vec<wasmedge_sdk::WasmValue>,
        _data: *mut std::ffi::c_void
    );

    // visibility of wrapper function
    let wrapper_visibility = item_fn.vis.clone();

    // get the name of the first argument
    let (ident_first_arg, mutability) = match &item_fn.sig.inputs[0] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => (pat_ident.ident.clone(), pat_ident.mutability),
            Pat::Wild(_) => (
                proc_macro2::Ident::new("_caller", proc_macro2::Span::call_site()),
                None,
            ),
            _ => panic!("The argument pattern of the first argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The first argument is a receiver"),
    };

    // get the name of the second argument
    let ident_second_arg = match &item_fn.sig.inputs[1] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => pat_ident.ident.clone(),
            Pat::Wild(_) => proc_macro2::Ident::new("_args", proc_macro2::Span::call_site()),
            _ => panic!("The argument pattern of the second argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The second argument is a receiver"),
    };

    // func body
    let fn_block = item_fn.block.clone();

    quote!(
        #wrapper_visibility fn #wrapper_fn_name_ident (#wrapper_fn_inputs) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)> {

            // create a Caller instance
            let #mutability #ident_first_arg = Caller::new(frame);

            let #ident_second_arg = args;

            Box::new(async move {
                #fn_block
            })
        }
    )
}

fn expand_async_host_func_with_three_args(item_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    // * define the signature of wrapper function
    // name of wrapper function
    let wrapper_fn_name_ident = item_fn.sig.ident.clone();
    // arguments of wrapper function
    let wrapper_fn_inputs: syn::punctuated::Punctuated<FnArg, syn::token::Comma> = parse_quote!(
        frame: wasmedge_sdk::CallingFrame,
        args: Vec<wasmedge_sdk::WasmValue>,
        data: *mut std::ffi::c_void
    );
    // visibility of wrapper function
    let wrapper_visibility = item_fn.vis.clone();

    // get the name of the first argument
    let (ident_first_arg, mutability) = match &item_fn.sig.inputs[0] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => (pat_ident.ident.clone(), pat_ident.mutability),
            Pat::Wild(_) => (
                proc_macro2::Ident::new("_caller", proc_macro2::Span::call_site()),
                None,
            ),
            _ => panic!("The argument pattern of the first argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The first argument is a receiver"),
    };

    // get the name of the second argument
    let ident_second_arg = match &item_fn.sig.inputs[1] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => pat_ident.ident.clone(),
            Pat::Wild(_) => proc_macro2::Ident::new("_args", proc_macro2::Span::call_site()),
            _ => panic!("The argument pattern of the second argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The second argument is a receiver"),
    };

    // get the name of the third argument
    let ident_third_arg = match &item_fn.sig.inputs[2] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => pat_ident.ident.clone(),
            Pat::Wild(_) => proc_macro2::Ident::new("_data", proc_macro2::Span::call_site()),
            _ => panic!("The argument pattern of the third argument is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("The third argument is a receiver"),
    };

    // get the type of the third argument
    let data_arg = item_fn.sig.inputs.last().unwrap().clone();
    let ty_third_arg = match &data_arg {
        FnArg::Typed(PatType { ref ty, .. }) => match **ty {
            syn::Type::Reference(syn::TypeReference { ref elem, .. }) => syn::TypePtr {
                star_token: parse_quote!(*),
                const_token: None,
                mutability: Some(parse_quote!(mut)),
                elem: elem.clone(),
            },
            syn::Type::Path(syn::TypePath { ref path, .. }) => match path.segments.last() {
                Some(segment) => {
                    let id = segment.ident.to_string();
                    match id == "Option" {
                        true => match segment.arguments {
                            syn::PathArguments::AngleBracketed(
                                syn::AngleBracketedGenericArguments { ref args, .. },
                            ) => {
                                let last_generic_arg = args.last();
                                match last_generic_arg {
                                    Some(arg) => match arg {
                                        syn::GenericArgument::Type(ty) => match ty {
                                            syn::Type::Reference(syn::TypeReference {
                                                ref elem,
                                                ..
                                            }) => syn::TypePtr {
                                                star_token: parse_quote!(*),
                                                const_token: None,
                                                mutability: Some(parse_quote!(mut)),
                                                elem: elem.clone(),
                                            },
                                            _ => panic!("Not found syn::Type::Reference"),
                                        },
                                        _ => {
                                            panic!("Not found syn::GenericArgument::Type")
                                        }
                                    },
                                    None => panic!("Not found the last GenericArgument"),
                                }
                            }
                            _ => panic!("Not found syn::PathArguments::AngleBracketed"),
                        },
                        false => panic!("Not found segment ident: Option"),
                    }
                }
                None => panic!("Not found path segments"),
            },
            _ => panic!("Unsupported syn::Type type"),
        },
        _ => panic!("Unsupported syn::FnArg type"),
    };

    // func body
    let fn_block = item_fn.block.clone();

    quote!(
        #wrapper_visibility fn #wrapper_fn_name_ident (#wrapper_fn_inputs) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)> {

            // create a Caller instance
            let #mutability #ident_first_arg = Caller::new(frame);

            let #ident_second_arg = args;

            // host context data
            let #ident_third_arg = unsafe { &mut *(data as #ty_third_arg) };

            Box::new(async move {
                #fn_block
            })
        }
    )
}

// ================== macros for wasmedge-sys ==================

#[doc(hidden)]
#[proc_macro_attribute]
pub fn sys_async_host_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let body_ast = parse_macro_input!(item as Item);
    if let Item::Fn(item_fn) = body_ast {
        if item_fn.sig.asyncness.is_none() {
            panic!("The function must be async");
        }

        match sys_expand_async_host_func(&item_fn) {
            Ok(token_stream) => token_stream.into(),
            Err(err) => err.to_compile_error().into(),
        }
    } else {
        TokenStream::new()
    }
}

fn sys_expand_async_host_func(item_fn: &syn::ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    // extract T from Option<&mut T>
    let ret = match &item_fn.sig.inputs.len() {
        2 => sys_expand_async_host_func_with_two_args(item_fn),
        3 => sys_expand_async_host_func_with_three_args(item_fn),
        _ => panic!("Invalid numbers of host function arguments"),
    };

    Ok(ret)
}

fn sys_expand_async_host_func_with_two_args(item_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    // function name
    let fn_name_ident = &item_fn.sig.ident;

    // function visibility
    let fn_visibility = &item_fn.vis;

    // generic types
    let fn_generics = &item_fn.sig.generics;

    // arguments
    let mut fn_inputs = item_fn.sig.inputs.clone();
    fn_inputs.push(parse_quote!(_: *mut std::os::raw::c_void));

    // function body
    let fn_block = &item_fn.block;

    quote!(
        #fn_visibility fn #fn_name_ident #fn_generics (#fn_inputs) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)> {
            Box::new(async move {
                #fn_block
            })
        }
    )
}

fn sys_expand_async_host_func_with_three_args(item_fn: &syn::ItemFn) -> proc_macro2::TokenStream {
    // function name
    let fn_name_ident = &item_fn.sig.ident;

    // function visibility
    let fn_visibility = &item_fn.vis;

    // generic types
    let fn_generics = &item_fn.sig.generics;

    // arguments
    let fn_inputs = &item_fn.sig.inputs;

    // function body
    let fn_block = &item_fn.block;

    quote!(
        #fn_visibility fn #fn_name_ident #fn_generics (#fn_inputs) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)> {
            Box::new(async move {
                #fn_block
            })
        }
    )
}

#[doc(hidden)]
#[proc_macro_attribute]
pub fn sys_host_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let body_ast = parse_macro_input!(item as Item);
    if let Item::Fn(item_fn) = body_ast {
        match sys_expand_host_func_new(&item_fn) {
            Ok(token_stream) => token_stream.into(),
            Err(err) => err.to_compile_error().into(),
        }
    } else {
        TokenStream::new()
    }
}

fn sys_expand_host_func_new(item_fn: &syn::ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    // * define the signature of wrapper function
    // name of wrapper function
    let wrapper_fn_name_ident = item_fn.sig.ident.clone();
    let wrapper_fn_name_literal = wrapper_fn_name_ident.to_string();
    // return type of wrapper function
    let wrapper_fn_return = item_fn.sig.output.clone();
    // visibility of wrapper function
    let wrapper_fn_visibility = item_fn.vis.clone();

    // * define the signature of inner function
    // name of inner function
    let inner_fn_name_literal = format!("inner_{wrapper_fn_name_literal}");
    let inner_fn_name_ident = syn::Ident::new(&inner_fn_name_literal, item_fn.sig.span());
    // arguments of inner function
    let inner_fn_inputs = item_fn.sig.inputs.clone();
    // return type of inner function
    let inner_fn_return = item_fn.sig.output.clone();
    // body of inner function
    let inner_fn_block = item_fn.block.clone();

    // extract the identities of the first two arguments
    let arg1 = match &item_fn.sig.inputs[0] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => pat_ident.ident.clone(),
            Pat::Wild(_) => proc_macro2::Ident::new("_", proc_macro2::Span::call_site()),
            _ => panic!("argument pattern is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("argument is a receiver"),
    };
    let arg2 = match &item_fn.sig.inputs[1] {
        FnArg::Typed(PatType { pat, .. }) => match &**pat {
            Pat::Ident(pat_ident) => pat_ident.ident.clone(),
            Pat::Wild(_) => proc_macro2::Ident::new("_", proc_macro2::Span::call_site()),
            _ => panic!("argument pattern is not a simple ident"),
        },
        FnArg::Receiver(_) => panic!("argument is a receiver"),
    };

    // extract T from Option<&mut T>
    let ret = match item_fn.sig.inputs.len() {
        2 => {
            // insert the third argument
            // let wrapper_fn_inputs = item_fn.sig.inputs.clone();
            let mut wrapper_fn_inputs = item_fn.sig.inputs.clone();
            wrapper_fn_inputs.push(parse_quote!(_data: *mut std::os::raw::c_void));

            quote!(
                #wrapper_fn_visibility fn #wrapper_fn_name_ident (#wrapper_fn_inputs) #wrapper_fn_return {
                    // define inner function
                    fn #inner_fn_name_ident (#inner_fn_inputs) #inner_fn_return {
                        #inner_fn_block
                    }

                    #inner_fn_name_ident(#arg1, #arg2)
                }
            )
        }
        3 => {
            let data_arg = item_fn.sig.inputs.last().unwrap().clone();
            let ty_ptr = match &data_arg {
                FnArg::Typed(PatType { ref ty, .. }) => match **ty {
                    syn::Type::Reference(syn::TypeReference { ref elem, .. }) => syn::TypePtr {
                        star_token: parse_quote!(*),
                        const_token: None,
                        mutability: Some(parse_quote!(mut)),
                        elem: elem.clone(),
                    },
                    syn::Type::Path(syn::TypePath { ref path, .. }) => match path.segments.last() {
                        Some(segment) => {
                            let id = segment.ident.to_string();
                            match id == "Option" {
                                true => match segment.arguments {
                                    syn::PathArguments::AngleBracketed(
                                        syn::AngleBracketedGenericArguments { ref args, .. },
                                    ) => {
                                        let last_generic_arg = args.last();
                                        match last_generic_arg {
                                            Some(arg) => match arg {
                                                syn::GenericArgument::Type(ty) => match ty {
                                                    syn::Type::Reference(syn::TypeReference {
                                                        ref elem,
                                                        ..
                                                    }) => syn::TypePtr {
                                                        star_token: parse_quote!(*),
                                                        const_token: None,
                                                        mutability: Some(parse_quote!(mut)),
                                                        elem: elem.clone(),
                                                    },
                                                    _ => panic!("Not found syn::Type::Reference"),
                                                },
                                                _ => {
                                                    panic!("Not found syn::GenericArgument::Type")
                                                }
                                            },
                                            None => panic!("Not found the last GenericArgument"),
                                        }
                                    }
                                    _ => panic!("Not found syn::PathArguments::AngleBracketed"),
                                },
                                false => panic!("Not found segment ident: Option"),
                            }
                        }
                        None => panic!("Not found path segments"),
                    },
                    _ => panic!("Unsupported syn::Type type"),
                },
                _ => panic!("Unsupported syn::FnArg type"),
            };

            // inputs of wrapper function
            let mut wrapper_fn_inputs = item_fn.sig.inputs.clone();
            wrapper_fn_inputs.pop();
            wrapper_fn_inputs.push(parse_quote!(data: *mut std::os::raw::c_void));

            // generate token stream
            quote!(
                #wrapper_fn_visibility fn #wrapper_fn_name_ident (#wrapper_fn_inputs) #wrapper_fn_return {
                    // define inner function
                    fn #inner_fn_name_ident (#inner_fn_inputs) #inner_fn_return {
                        #inner_fn_block
                    }

                    let data = unsafe { &mut *(data as #ty_ptr) };

                    #inner_fn_name_ident(#arg1, #arg2, data)
                }
            )
        }
        _ => panic!("Invalid numbers of host function arguments"),
    };

    Ok(ret)
}

// ================== macros for wasmedge-sys wasi host functions ==================

#[doc(hidden)]
#[proc_macro_attribute]
pub fn sys_wasi_host_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let body_ast = parse_macro_input!(item as Item);
    if let Item::Fn(item_fn) = body_ast {
        match sys_expand_wasi_host_func(&item_fn) {
            Ok(token_stream) => token_stream.into(),
            Err(err) => err.to_compile_error().into(),
        }
    } else {
        TokenStream::new()
    }
}

fn sys_expand_wasi_host_func(item_fn: &syn::ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    // * define the signature of wrapper function
    // name of wrapper function
    let fn_name_ident = &item_fn.sig.ident;
    // return type of wrapper function
    let fn_return = &item_fn.sig.output;
    // visibility of wrapper function
    let fn_visibility = &item_fn.vis;

    // extract T from Option<&mut T>
    let ret = match item_fn.sig.inputs.len() {
        3 => {
            let fn_generics = &item_fn.sig.generics;

            // inputs of wrapper function
            let fn_inputs = &item_fn.sig.inputs;

            let fn_block = item_fn.block.clone();

            quote!(
                #fn_visibility fn #fn_name_ident #fn_generics (#fn_inputs) #fn_return
                    #fn_block
            )
        }
        _ => panic!("Invalid numbers of host function arguments"),
    };

    Ok(ret)
}

#[doc(hidden)]
#[proc_macro_attribute]
pub fn sys_async_wasi_host_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let body_ast = parse_macro_input!(item as Item);
    if let Item::Fn(item_fn) = body_ast {
        if item_fn.sig.asyncness.is_none() {
            panic!("The function must be async");
        }

        match sys_expand_async_wasi_host_func(&item_fn) {
            Ok(token_stream) => token_stream.into(),
            Err(err) => err.to_compile_error().into(),
        }
    } else {
        TokenStream::new()
    }
}

fn sys_expand_async_wasi_host_func(item_fn: &syn::ItemFn) -> syn::Result<proc_macro2::TokenStream> {
    // extract T from Option<&mut T>
    let ret = match &item_fn.sig.inputs.len() {
        2 => sys_expand_async_wasi_host_func_with_two_args(item_fn),
        3 => sys_expand_async_wasi_host_func_with_three_args(item_fn),
        _ => panic!("Invalid numbers of host function arguments"),
    };

    Ok(ret)
}

fn sys_expand_async_wasi_host_func_with_two_args(
    item_fn: &syn::ItemFn,
) -> proc_macro2::TokenStream {
    // function name
    let fn_name_ident = &item_fn.sig.ident;

    // function visibility
    let fn_visibility = &item_fn.vis;

    // generic types
    let fn_generics = &item_fn.sig.generics;

    // arguments
    let mut fn_inputs = item_fn.sig.inputs.clone();
    fn_inputs.push(parse_quote!(_: *mut std::os::raw::c_void));

    // function body
    let fn_block = &item_fn.block;

    quote!(
        #fn_visibility fn #fn_name_ident #fn_generics (#fn_inputs) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)> {
            Box::new(async move {
                #fn_block
            })
        }
    )
}

fn sys_expand_async_wasi_host_func_with_three_args(
    item_fn: &syn::ItemFn,
) -> proc_macro2::TokenStream {
    // function name
    let fn_name_ident = &item_fn.sig.ident;

    // function visibility
    let fn_visibility = &item_fn.vis;

    // generic types
    let fn_generics = &item_fn.sig.generics;

    // arguments
    let fn_inputs = &item_fn.sig.inputs;

    // function body
    let fn_block = &item_fn.block;

    quote!(
        #fn_visibility fn #fn_name_ident #fn_generics (#fn_inputs) -> Box<(dyn std::future::Future<Output = Result<Vec<WasmValue>, HostFuncError>> + Send)> {
            Box::new(async move {
                #fn_block
            })
        }
    )
}