nadi_plugin 0.8.0

Macro library to write plugins for nadi system using nadi_core
Documentation
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
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
//! Procedural Macros for plugin development for NADI system.
//!
//! Do not use this library by itself, it should be reexported from
//! [`nadi_core`] crate
use convert_case::{Case, Casing};
use std::collections::HashMap;

use proc_macro::TokenStream;
use quote::{ToTokens, format_ident, quote, quote_spanned};
use syn::{
    Attribute, DeriveInput, Expr, FnArg, Ident, ItemFn, ItemMod, Lit, MetaNameValue, Type,
    parse_macro_input, punctuated::Punctuated, token::Comma,
};

#[derive(PartialEq)]
enum FuncType {
    Env,
    Node,
    Network,
}

impl std::fmt::Display for FuncType {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(
            f,
            "{}",
            match self {
                FuncType::Env => "Env",
                FuncType::Node => "Node",
                FuncType::Network => "Network",
            }
        )
    }
}

/// Idents and Path for from_attr and try_from_attr
fn nadi_trait_idents(relaxed: bool) -> (proc_macro2::TokenStream, Ident, Ident) {
    let (tr, func1, func2) = if relaxed {
        (
            format_ident!("FromAttributeRelaxed"),
            format_ident!("from_attr_relaxed"),
            format_ident!("try_from_attr_relaxed"),
        )
    } else {
        (
            format_ident!("FromAttribute"),
            format_ident!("from_attr"),
            format_ident!("try_from_attr"),
        )
    };
    (quote! {::nadi_core::attrs::#tr}, func1, func2)
}

fn nadi_struct_name(name: &Ident, suff: &str) -> Ident {
    format_ident!("{}{suff}", name.to_string().to_case(Case::UpperCamel))
}

fn nadi_func_impl(ft: &FuncType) -> proc_macro2::TokenStream {
    match ft {
        FuncType::Env => quote! {::nadi_core::functions::EnvFunction},
        FuncType::Node => quote! {::nadi_core::functions::NodeFunction},
        FuncType::Network => quote! {::nadi_core::functions::NetworkFunction},
    }
}

#[proc_macro_derive(FromAttribute)]
pub fn from_attribute_derive(input: TokenStream) -> TokenStream {
    from_attr_derive(input, false)
}

#[proc_macro_derive(FromAttributeRelaxed)]
pub fn from_attribute_relaxed_derive(input: TokenStream) -> TokenStream {
    from_attr_derive(input, true)
}

/// this should support automatically deriving the FromAttribute trait for the following complex types
/// - Struct(ty) => wrapper values like this as long as ty has FromAttribute
/// - Struct {x:.., y:..}  => struct values will be made from Table() as long as each field type has FromAttribute
/// - Enum{...} => enum values will be made for the first type that is matched from Attribute types as long as each one has FromAttribute
fn from_attr_derive(input: TokenStream, relaxed: bool) -> TokenStream {
    let (trt, func, try_func) = nadi_trait_idents(relaxed);
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;
    let name_s = name.to_string();
    let data = input.data.clone();
    let conversion = match data {
        syn::Data::Struct(st) => {
            match st.fields {
                syn::Fields::Named(flds) => {
                    // try to parse a Table value into the fields of this struct
                    let conv: Vec<_> = flds.named.iter().map(|f| {
			let i = &f.ident;
			let is = i.as_ref().map(|l| l.to_string()).expect("should be named");
			quote!{
			    let val = match attrmap.get(#is) {
				Some(v) => v,
				None => return Err(format!("FieldError: Field {} not found in the value for {}", #is, #name_s)),
			    };
			    let #i = #trt :: #try_func (val)?;
			}
		    }).collect();
                    let names = flds.named.iter().map(|f| &f.ident);
                    quote! {
                    let attrmap: ::nadi_core::attrs::AttrMap = ::nadi_core::attrs::FromAttribute::try_from_attr (value)?;
                    #(#conv)*
                    Ok(Self {
                        #(#names),*
                    })
                    }
                }
                syn::Fields::Unnamed(_) => {
                    quote! {
                    Ok(Self(#trt :: #func (value)?))
                    }
                }
                _ => panic!("Not supported"),
            }
        }
        syn::Data::Enum(en) => {
            // try each variant and return the first one that succeeds
            let vars: Vec<_> = en
                .variants
                .iter()
                .map(|v| {
                    let i = &v.ident;
                    quote! {
                        if let Some(val) = #trt :: #func (value) {
                        return Ok(Self::#i(val));
                        }
                    }
                })
                .collect();
            let names: Vec<String> = en
                .variants
                .iter()
                .map(|v| {
                    v.fields
                        .to_token_stream()
                        .to_string()
                        .trim_matches(['(', ')'])
                        .to_string()
                })
                .collect();
            // TODO extra () for unnamed fields should be renamed later
            let names = names.join(" | ");
            quote! {
            #(#vars)*
            Err(format!("Incorrect Type: got {} instead of one of: [ {} ]", value.type_name(), #names))
            }
        }
        syn::Data::Union(_) => {
            panic!("Union derive not supported!")
        }
    };

    let expanded = quote! {
        impl #trt for #name {
            fn #func (value: &Attribute) -> Option<Self>{
        #trt :: #try_func(value).ok()
            }
            fn #try_func (value: &Attribute) -> Result<Self, String> {
        #conversion
            }
    }
    };
    // println!("{}", expanded);
    TokenStream::from(expanded)
}

/// register this function as a node function on nadi plugin
#[proc_macro_attribute]
pub fn env_func(args: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as ItemFn);
    let args = parse_macro_input!(args with Punctuated<MetaNameValue, Comma>::parse_terminated);
    nadi_func_inner(args, item, FuncType::Env).into()
}

/// register this function as a node function on nadi plugin
#[proc_macro_attribute]
pub fn node_func(args: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as ItemFn);
    let args = parse_macro_input!(args with Punctuated<MetaNameValue, Comma>::parse_terminated);
    nadi_func_inner(args, item, FuncType::Node).into()
}

/// register this function as a network function on nadi plugin
#[proc_macro_attribute]
pub fn network_func(args: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as ItemFn);
    let args = parse_macro_input!(args with Punctuated<MetaNameValue, Comma>::parse_terminated);
    nadi_func_inner(args, item, FuncType::Network).into()
}

#[derive(Clone, Copy, Default, PartialEq)]
enum FuncArgType {
    #[default]
    Arg,
    Relaxed,
    Args,
    KwArgs,
}

const FUNC_ARG_ATTRS: [(&str, FuncArgType); 3] = [
    ("args", FuncArgType::Args),
    ("kwargs", FuncArgType::KwArgs),
    ("relaxed", FuncArgType::Relaxed),
];

fn nadi_func_inner(
    args: Punctuated<MetaNameValue, Comma>,
    item: ItemFn,
    ft: FuncType,
) -> proc_macro2::TokenStream {
    let default_args: HashMap<Ident, Expr> = args
        .into_iter()
        .map(|p| (p.path.segments.first().unwrap().ident.clone(), p.value))
        .collect();
    let arg0 = if FuncType::Env == ft {
        None
    } else {
        item.sig.inputs.first()
    };
    let func_args: Vec<(&Ident, &Type, FuncArgType)> = item
        .sig
        .inputs
        .iter()
        // skip first argument, node or network
        .skip((FuncType::Env != ft) as usize)
        .map(get_fn_arg)
        .collect();
    let warnings = check_args_kwargs_order(&func_args, &default_args);

    let func_struct_name = nadi_struct_name(&item.sig.ident, &ft.to_string());

    let name_func = get_name_func(&item);
    let code_func = get_code_func(&item);
    let (call_func, default_exprs) = get_call_func(
        &item,
        arg0,
        &ft,
        &func_args,
        &default_args,
        &func_struct_name,
    );
    let help_func = get_help_func(&item);
    let signature_func = get_signature_func(&item, &ft, &default_args, default_exprs);
    let impl_trait = nadi_func_impl(&ft);

    let clean_func = clean_function(&item);

    quote! {
    #warnings

        #[derive(Debug, Clone)]
        pub struct #func_struct_name;

        impl #impl_trait for #func_struct_name {
            #name_func
            #code_func
            #help_func
            #signature_func
            #call_func
        }

        impl  #func_struct_name {
            #clean_func
        }
    }
}

/// Invalid argument names = task system keywords
const INVALID_ARG_NAME: [&str; 63] = [
    "clear",  // TaskKeyword::Clear
    "import", // TaskKeyword::Import
    "exec",   // TaskKeyword::Exec
    "from",   // TaskKeyword::From
    "node",   // TaskKeyword::Node
    "network",
    "net",      // TaskKeyword::Network
    "networks", // TaskKeyword::Networks
    "networksmap",
    "netm",   // TaskKeyword::NetworksMap
    "env",    // TaskKeyword::Env
    "exit",   // TaskKeyword::Exit
    "end",    // TaskKeyword::End
    "help",   // TaskKeyword::Help
    "input",  // TaskKeyword::Input
    "inputs", // TaskKeyword::Inputs
    "inputsmap",
    "im",      // TaskKeyword::InputsMap
    "output",  // TaskKeyword::Output
    "outputs", // TaskKeyword::Outputs
    "outputsmap",
    "om",    // TaskKeyword::OutputsMap
    "edge",  // TaskKeyword::Edge
    "edges", // TaskKeyword::Edges
    "edgesmap",
    "em",    // TaskKeyword::EdgesMap
    "nodes", // TaskKeyword::Nodes
    "nodesmap",
    "nm",    // TaskKeyword::NodesMap
    "root",  // TaskKeyword::Root
    "roots", // TaskKeyword::Roots
    "rootsmap",
    "rm",     // TaskKeyword::RootsMap
    "leaf",   // TaskKeyword::Leaf
    "leaves", // TaskKeyword::Leaves
    "leavesmap",
    "lm",    // TaskKeyword::LeavesMap
    "if",    // TaskKeyword::If
    "else",  // TaskKeyword::Else
    "while", // TaskKeyword::While
    "try",   // TaskKeyword::Try
    "catch", // TaskKeyword::Catch
    "in",    // TaskKeyword::In
    "match", // TaskKeyword::Match
    "hook",  // TaskKeyword::Hook
    "local",
    "loc",    // TaskKeyword::Local
    "struct", // TaskKeyword::Struct
    "function",
    "func",     // TaskKeyword::Function
    "return",   // TaskKeyword::Return
    "break",    // TaskKeyword::Break
    "continue", // TaskKeyword::Continue
    "error",    // TaskKeyword::Error
    "for",      // TaskKeyword::For
    "map",      // TaskKeyword::Map
    "attrs",    // TaskKeyword::Attrs
    "loop",     // TaskKeyword::Loop
    "progress",
    "prog",  // TaskKeyword::Progress
    "do",    // TaskKeyword::Do
    "par",   // TaskKeyword::Par
    "dopar", // TaskKeyword::DoPar
];

fn check_args_kwargs_order(
    args: &[(&Ident, &Type, FuncArgType)],
    default_args: &HashMap<Ident, Expr>,
) -> proc_macro2::TokenStream {
    let mut warnings: Vec<proc_macro2::TokenStream> = default_args
        .keys()
        .filter_map(|id| {
            if INVALID_ARG_NAME.contains(&id.to_string().as_str()) {
                Some(quote_spanned! {
                id.span() =>
                    compile_error!("Invalid name for the argument (keyword)");
                })
            } else if !args.iter().any(|a| a.0 == id) {
                Some(quote_spanned! {
                id.span() =>
                    compile_error!("Argument not in the inner function");
                })
            } else {
                None
            }
        })
        .collect();
    let mut flag = false;
    for (a, t, at) in args {
        if type_is_opt(t) || default_args.contains_key(a) || matches!(at, FuncArgType::KwArgs) {
            flag = true;
        } else if flag {
            warnings.push(quote_spanned! {
                a.span()=> compile_error!("Positional argument after default argument(s)");
            });
        }
    }

    quote! { #(#warnings)* }
}

/// Clean the function of function argument attributes like #[args], ...
fn clean_function(func: &ItemFn) -> ItemFn {
    let mut func = func.clone();
    for arg in &mut func.sig.inputs {
        match arg {
            syn::FnArg::Typed(a) => {
                let attrs = std::mem::take(&mut a.attrs);
                let (_, remain): (Vec<_>, Vec<_>) = attrs.into_iter().partition(|at| {
                    // remove all attrs for function arg, and the doc attribute
                    FUNC_ARG_ATTRS
                        .iter()
                        .map(|a| a.0)
                        .chain(["doc"])
                        .any(|a| at.path().is_ident(a))
                });

                a.attrs = remain;
            }
            _ => panic!("unsuported args"),
        }
    }
    func
}

fn get_fn_arg(arg: &FnArg) -> (&Ident, &Type, FuncArgType) {
    match arg {
        syn::FnArg::Typed(arg) => {
            let t: FuncArgType = FUNC_ARG_ATTRS
                .iter()
                .filter(|a| arg.attrs.iter().any(|at| at.path().is_ident(a.0)))
                .map(|a| a.1)
                .next()
                .unwrap_or_default();
            match arg.pat.as_ref() {
                syn::Pat::Ident(i) => (&i.ident, arg.ty.as_ref(), t),
                _ => panic!("Invalid Argument Type for Nadi function"),
            }
        }
        _ => panic!("Invalid Argument Type for Nadi function"),
    }
}

/// Register the plugin for NADI system. This should be on the top
/// level of the `mod`, with access to all the functions so it can
/// register them
///
/// # Example Use:
/// ```rust,ignore
/// // This requies you to have nadi_core in your direct dependency
/// #[nadi_plugin::nadi_plugin]
/// mod plugin_name {
///     #[nadi_plugin::node_func]
///     fn do_something(node: &mut NodeInner) {
///     // do something here
///     }
/// }
/// ```
///
/// Only one instance of `mod` should be exported as plugin for
/// external plugins compiled to cdynlib.
#[proc_macro_attribute]
pub fn nadi_plugin(args: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as ItemMod);
    let args = parse_macro_input!(args with Punctuated<MetaNameValue, Comma>::parse_terminated);
    nadi_export_plugin(args, item, true).into()
}

/// Register the `mod` as an internal plugin, only to be used on
/// plugins compiled in `nadi_core` crate. This should also be in the
/// top of the `mod` definition so it can see all the functions.
#[proc_macro_attribute]
pub fn nadi_internal_plugin(args: TokenStream, item: TokenStream) -> TokenStream {
    let item = parse_macro_input!(item as ItemMod);
    let args = parse_macro_input!(args with Punctuated<MetaNameValue, Comma>::parse_terminated);
    nadi_export_plugin(args, item, false).into()
}

fn nadi_export_plugin(
    _args: Punctuated<MetaNameValue, Comma>,
    item: ItemMod,
    external: bool,
) -> proc_macro2::TokenStream {
    let name = &item.ident;
    let name_s = if external {
        name.to_string().to_lowercase()
    } else {
        name.to_string().to_uppercase()
    };
    let name_mod = nadi_struct_name(name, "Mod");
    let env_funcs = get_nadi_functions(&item, "env_func");
    let node_funcs = get_nadi_functions(&item, "node_func");
    let network_funcs = get_nadi_functions(&item, "network_func");
    let regis_env_funcs = env_funcs
        .iter()
        .map(|n| (n.to_string(), nadi_struct_name(n, "Env")))
        .map(|(alias, n)| {
            let alias = (!external).then(|| {
                quote! {
                    let name = format!("{}.{}", #name_s, #alias);
                    nf.register_alias(name, #alias .to_string(),  ::nadi_core::tasks::FunctionType::Env);
                }
            });
            quote! {
            #alias

                        nf.register_env_function(
                    #name_s,
                            ::nadi_core::functions::EnvFunction_TO::from_value(
                    #n,
                    ::nadi_core::abi_stable::sabi_trait::TD_CanDowncast
                            )
                );
                    }
        });
    let regis_node_funcs = node_funcs
        .iter()
        .map(|n| (n.to_string(), nadi_struct_name(n, "Node")))
        .map(|(alias, n)| {
            let alias = (!external).then(|| {
                quote! {
                    let name = format!("{}.{}", #name_s, #alias);
                    nf.register_alias(name, #alias .to_string(),  ::nadi_core::tasks::FunctionType::Node);
                }
            });
            quote! {
            #alias
                    nf.register_node_function(
                #name_s,
                        ::nadi_core::functions::NodeFunction_TO::from_value(
                #n,
                ::nadi_core::abi_stable::sabi_trait::TD_CanDowncast
                        )
            );
                }
        });
    let regis_network_funcs = network_funcs
        .iter()
        .map(|n| (n.to_string(), nadi_struct_name(n, "Network")))
        .map(|(alias, n)| {
            let alias = (!external).then(|| {
                quote! {
                    let name = format!("{}.{}", #name_s, #alias);
                    nf.register_alias(name, #alias .to_string(),::nadi_core::tasks::FunctionType::Network);
                }
            });
            quote! {
            #alias
                    nf.register_network_function(
                #name_s,
                        ::nadi_core::functions::NetworkFunction_TO::from_value(
                            #n,
                            ::nadi_core::abi_stable::sabi_trait::TD_CanDowncast
                        )
                    );
                }
        });

    if external {
        quote! {
            #[::nadi_core::abi_stable::export_root_module]
            pub fn get_library() -> ::nadi_core::plugins::NadiExternalPlugin_Ref {
        ::nadi_core::abi_stable::prefix_type::PrefixTypeTrait::leak_into_prefix(
            ::nadi_core::plugins::NadiExternalPlugin {
            register_functions,
            plugin_name,
            })
            }

            #[::nadi_core::abi_stable::sabi_extern_fn]
            fn plugin_name() -> ::nadi_core::abi_stable::std_types::RString {
                #name_s .into()
            }

            #[::nadi_core::abi_stable::sabi_extern_fn]
            fn register_functions(nf: &mut ::nadi_core::functions::NadiFunctions) {

                #(#regis_env_funcs)*

                #(#regis_node_funcs)*

                #(#regis_network_funcs)*
            }

            use #name::*;

            #item
        }
    } else {
        quote! {
            pub struct #name_mod;

            impl ::nadi_core::plugins::NadiPlugin for #name_mod {
        fn name(&self) -> ::nadi_core::abi_stable::std_types::RString {
                    #name_s .into()
        }
        fn register(&self, nf: &mut ::nadi_core::functions::NadiFunctions) {

            #(#regis_env_funcs)*

            #(#regis_node_funcs)*

            #(#regis_network_funcs)*
        }
            }

            use #name::*;

            #item
        }
    }
}

fn get_nadi_functions<'a>(item: &'a ItemMod, funct: &'_ str) -> Vec<&'a Ident> {
    if let Some((_, cont)) = &item.content {
        cont.iter()
            .filter_map(|c| {
                if let syn::Item::Fn(f) = c {
                    Some(f)
                } else {
                    None
                }
            })
            .filter_map(|f| {
                if f.attrs.iter().any(|a| match &a.meta {
                    syn::Meta::Path(p) => p.is_ident(funct),
                    syn::Meta::List(l) => l.path.is_ident(funct),
                    _ => false,
                }) {
                    Some(&f.sig.ident)
                } else {
                    None
                }
            })
            .collect()
    } else {
        vec![]
    }
}

fn get_name_func(item: &ItemFn) -> proc_macro2::TokenStream {
    let func_name = item.sig.ident.to_string();

    quote! {
        fn name(&self) -> ::nadi_core::abi_stable::std_types::RString {
            #func_name .into()
        }
    }
}

fn get_code_func(item: &ItemFn) -> proc_macro2::TokenStream {
    let func_code = prettyplease::unparse(
        &syn::parse2(item.to_token_stream()).expect("code should be valid for prettyplease"),
    );

    quote! {
    fn code(&self) -> ::nadi_core::abi_stable::std_types::RString {
    #func_code .into()
    }}
}

fn get_call_func(
    item: &ItemFn,
    arg0: Option<&FnArg>,
    ft: &FuncType,
    args: &[(&Ident, &Type, FuncArgType)],
    defaults: &HashMap<Ident, Expr>,
    func_struct_name: &Ident,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
    let mut defaults_expr: Vec<proc_macro2::TokenStream> = Vec::new();
    let ret_err = quote! { ::nadi_core::functions::FunctionRet::Error };
    let mut argc: usize = 0;
    let mut kwonly = false;
    let extract_args: Vec<proc_macro2::TokenStream> = args
        .iter()
        .map(|(arg, ty, at)| {
            argc += 1;
            let arg_name = arg.to_string();
            let ty_name = ty.to_token_stream().to_string();
            let arg_func_call = match at {
                FuncArgType::Arg if kwonly => quote! { ctx.just_kwarg (#arg_name) },
                FuncArgType::Arg => quote! { ctx.arg_kwarg (#argc - 1, #arg_name)},
                FuncArgType::Relaxed if kwonly => quote! { ctx.just_kwarg_relaxed (#arg_name)},
                FuncArgType::Relaxed => quote! { ctx.arg_kwarg_relaxed (#argc - 1, #arg_name)},
                FuncArgType::Args => {
                    kwonly = true;
                    return if let Type::Path(p) = ty
                        && p.path.is_ident("FunctionArgs")
                    {
                        quote! {
                                    let #arg: #ty = ctx.args();
                        }
                    } else {
                        quote! {
                                    let #arg: #ty = match ctx.try_args() {
                            Ok(v)=>v,
                            Err(e) => return #ret_err(e),
                        };
                        }
                    };
                }
                FuncArgType::KwArgs => {
                    kwonly = true;
                    return if let Type::Path(p) = ty
                        && p.path.is_ident("FunctionKwArgs")
                    {
                        quote! {
                            let #arg: #ty = ctx.kwargs();
                        }
                    } else {
                        quote! {
                                    let #arg: #ty = match ctx.try_kwargs(){
                            Ok(v)=>v,
                            Err(e) => return #ret_err(e),
                        };
                                }
                    };
                }
            };
            let def = if let Some(val) = defaults.get(arg) {
                let warn = match ty {
                    Type::Reference(r) => {
                        // mut reference on the network functions are
                        // useless as they are one time execution; in
                        // node function they might have unexpected
                        // behaviour as the node functions are
                        // supposed to be able to run in parallel
                        r.mutability.map(|m| {
                            quote_spanned! {
                                m.span=> compile_error!(
                                "Mutable Reference not supported for nadi function args"
                                );
                            }
                        })
                    }
                    _ => None,
                };
                defaults_expr.push(quote! {
                    let #arg : #ty = #val .into();
                });
                quote! {
                        #warn
                ::std::convert::Into::<#ty>::into(#val)
                    }
            } else if type_is_opt(ty) {
                quote!(None)
            } else {
                quote! {
                        return #ret_err (
                format!("Argument {} ({} [{}]) is required", #argc, #arg_name, #ty_name).into()
                        );
                    }
            };
            let patterns = quote! {
                Some(Ok(v)) => v,
                Some(Err(e)) => return #ret_err (e.into()),
                None => {#def},
            };

            quote! {
                let #arg : #ty = match #arg_func_call {
                #patterns
                };
            }
        })
        .collect();
    let args_n: Vec<proc_macro2::TokenStream> = args
        .iter()
        .map(|(arg, _, _)| arg.into_token_stream())
        .collect();
    let func_name = &item.sig.ident;
    let (fname, arg0, fcall) = match ft {
        FuncType::Env => (quote! {call}, quote! {}, quote! {#func_name(#(#args_n),*)}),
        _ => {
            let a0 = get_fn_arg(arg0.expect("Should have at least one argument"));
            let arg0_name = a0.0;
            let arg0_ty = a0.1;
            let fname = match &arg0_ty {
                syn::Type::Reference(r) => {
                    if r.mutability.is_some() {
                        quote! {call_mut}
                    } else {
                        quote! {call}
                    }
                }
                _ => panic!("First argument should be a reference"),
            };
            (
                fname,
                quote! {#arg0_name : #arg0_ty,},
                quote! {#func_name(#arg0_name, #(#args_n),*)},
            )
        }
    };
    let call_func = quote! {
            fn #fname(&self,
                    #arg0
                    ctx: &::nadi_core::functions::FunctionCtx)
                    -> ::nadi_core::functions::FunctionRet {

                #(#extract_args)*
        ::nadi_core::functions::FunctionRet::from(
                    #func_struct_name :: #fcall
                )
            }
    };
    let default_exprs = quote! {
    #(#defaults_expr)*
    };
    (call_func, default_exprs)
}

fn get_help_func(item: &ItemFn) -> proc_macro2::TokenStream {
    let docs = get_doc(&item.attrs);
    quote! {
        fn help(&self) -> ::nadi_core::abi_stable::std_types::RString {
    #docs .into()
        }
    }
}

// HACK ignoring the path and assuming anything::Option is Option
// FIX: move the option logic to traits, so it is automatically handled while resolving arguments
/// Checks if a type is Option
///
/// Any type with the name Option as the type name before the generics
/// is considered as an option type.
fn type_is_opt(ty: &Type) -> bool {
    // if let Type::Path(p) = ty {
    //     p.path.is_ident("Option")
    // } else {
    //     false
    // }
    let ty = ty.to_token_stream().to_string();
    let tt = ty
        .split('<')
        .next()
        .unwrap_or_default()
        .split("::")
        .last()
        .unwrap_or_default()
        .trim();
    tt == "Option" || tt == "ROption"
}

fn get_signature_func(
    item: &ItemFn,
    ft: &FuncType,
    default_args: &HashMap<Ident, Expr>,
    default_exprs: proc_macro2::TokenStream,
) -> proc_macro2::TokenStream {
    let args: Vec<proc_macro2::TokenStream> = item
        .sig
        .inputs
        .iter()
        .skip((FuncType::Env != *ft) as usize)
        .map(|a| {
            match a {
                syn::FnArg::Typed(a) => {
                    match a.pat.as_ref() {
                        syn::Pat::Ident(i) => {
                            let doc = get_doc(&a.attrs);
                            let (n, t) = (
                                i.ident.to_string(),
                                a.ty.as_ref().into_token_stream().to_string(),
                            );
                            // args and kwargs function signature
                            let ft = if a.attrs.iter().any(|at| at.path().is_ident("args")) {
                                quote! { Args }
                            } else if a.attrs.iter().any(|at| at.path().is_ident("kwargs")) {
                                quote! { KwArgs }
                            } else if default_args.contains_key(&i.ident) {
                                let v = format!("{{{}:?}}", i.ident);
                                quote! { DefArg(format!(#v) .into()) }
                            } else if type_is_opt(&a.ty) {
                                quote! { OptArg }
                            } else {
                                quote! { Arg }
                            };

                            quote! {
                            ::nadi_core::functions::FuncArg {
                                            name: #n .into(),
                                            ty: #t .into(),
                                            help: #doc .into(),
                                category: ::nadi_core::functions::FuncArgType:: #ft
                            }
                            }
                        }
                        _ => panic!("Not supported"),
                    }
                }
                _ => panic!("Not supported"),
            }
        })
        .collect();

    // function signature showing the function name, arguments and
    // their default values
    quote! {
        fn args(&self) -> ::nadi_core::abi_stable::std_types::RVec<
        ::nadi_core::functions::FuncArg
        > {
            #default_exprs
        vec![
        #(#args),*
        ] .into()
        }
    }
}

/// collect doc attributes
fn get_doc(attrs: &[Attribute]) -> String {
    let docs: Vec<String> = attrs
        .iter()
        .filter(|a| a.path().is_ident("doc"))
        .filter_map(|a| match &a.meta {
            syn::Meta::NameValue(val) => match &val.value {
                Expr::Lit(lit) => match &lit.lit {
                    Lit::Str(c) => {
                        let c = c.value();
                        Some(c.trim_matches(' ').to_string())
                    }
                    _ => None,
                },
                _ => None,
            },
            _ => None,
        })
        .collect();
    format_docstrings(docs.join("\n"))
}

fn format_docstrings(string: String) -> String {
    match string.lines().count() {
        0 => {
            // panic!("Please add at least one line of documentation");
            String::new()
        }
        1 => string.trim().to_string(),
        _ => {
            let num_leading = string
                .lines()
                .skip(1)
                .filter(|s| !s.is_empty())
                .filter_map(|l| l.chars().position(|c| !c.is_whitespace()))
                .min()
                .unwrap_or(0);
            let lines = string
                .lines()
                .skip(1)
                .map(|line| {
                    if line.len() > num_leading {
                        &line[num_leading..]
                    } else {
                        line
                    }
                })
                .map(|l| l.trim_end())
                .collect::<Vec<_>>()
                .join("\n");
            format!(
                "{}\n{}",
                string
                    .lines()
                    .next()
                    .expect("There should be at least one line of documentation"),
                lines
            )
        }
    }
}

// Error: "procedural macro API is used outside of a procedural macro"
// this error won't let us do much, might have to do a proper refactor
// for testing

#[cfg(test)]
mod test {
    use super::*;
    use rstest::*;
    use syn::parse_quote;

    #[rstest]
    #[case(parse_quote!(Option<i32>), true)]
    #[case(parse_quote!(i32), false)]
    #[case(parse_quote!(OptionT), false)]
    #[case(parse_quote!(std::core::Option<i32>), true)]
    // this could be a type alias, so anything with "Option", but get_opt_type will fail
    #[case(parse_quote!(some_crate::Option), true)]
    #[case(parse_quote!(Option<some_crate::CustomVec<i32>>), true)]
    #[case(parse_quote!(std::core::Option<some_crate::CustomVec<i32>>), true)]
    fn test_type_is_opt(#[case] ty: Type, #[case] is_opt: bool) {
        assert_eq!(type_is_opt(&ty), is_opt);
    }

    #[test]
    fn test_clean_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
            fn func_name(
        node: &NodeInner,
            /// Document for val
        val: i64,
        #[relaxed]
        val2: String,
            ) {
              todo!()
                }
        };
        let clean = clean_function(&item);
        let clean = quote!(#clean).to_string();
        assert!(!clean.contains("Document for val"));
        assert!(!clean.contains("relaxed"));
        assert!(clean.contains("Document for Function"));
    }

    #[test]
    fn count_node_functions() {
        // can't find a way to save this as static; maybe add them in rstest fixure?
        let item: syn::ItemMod = parse_quote! {
        mod plugin {
        #[node_func]
        fn func_one(node: &NodeInner) {
          todo!()
        }

        #[node_func]
        fn func_two(node: &NodeInner, val: i64) {
          todo!()
        }

        #[node_func(val=12)]
        fn func_three(node: &NodeInner, val: i64) {
          todo!()
        }
        }
                };

        let env_funcs = get_nadi_functions(&item, "env_func");
        let node_funcs = get_nadi_functions(&item, "node_func");
        let network_funcs = get_nadi_functions(&item, "network_func");
        assert!(env_funcs.is_empty());
        assert!(network_funcs.is_empty());

        let node_funcs: Vec<String> = node_funcs.iter().map(|i| i.to_string()).collect();
        assert_eq!(node_funcs, vec!["func_one", "func_two", "func_three"])
    }

    #[test]
    fn count_network_functions() {
        let item: syn::ItemMod = parse_quote! {
        mod plugin {
        #[network_func]
        fn func_one(net: &Network) {
          todo!()
        }

        #[network_func]
        fn func_two(net: &Network, val: i64) {
          todo!()
        }

        #[network_func(val=12)]
        fn func_three(net: &Network, val: i64) {
          todo!()
        }
        }
                };

        let env_funcs = get_nadi_functions(&item, "env_func");
        let node_funcs = get_nadi_functions(&item, "node_func");
        let network_funcs = get_nadi_functions(&item, "network_func");
        assert!(env_funcs.is_empty());
        assert!(node_funcs.is_empty());

        let network_funcs: Vec<String> = network_funcs.iter().map(|i| i.to_string()).collect();
        assert_eq!(network_funcs, vec!["func_one", "func_two", "func_three"])
    }

    #[test]
    fn count_env_functions() {
        let item: syn::ItemMod = parse_quote! {
        mod plugin {
        #[env_func]
        fn func_one(net: &Network) {
          todo!()
        }

        #[env_func]
        fn func_two(net: &Network, val: i64) {
          todo!()
        }

        #[env_func(val=12)]
        fn func_three(net: &Network, val: i64) {
          todo!()
        }
        }
                };

        let network_funcs = get_nadi_functions(&item, "network_func");
        let node_funcs = get_nadi_functions(&item, "node_func");
        let env_funcs = get_nadi_functions(&item, "env_func");
        assert!(network_funcs.is_empty());
        assert!(node_funcs.is_empty());

        let env_funcs: Vec<String> = env_funcs.iter().map(|i| i.to_string()).collect();
        assert_eq!(env_funcs, vec!["func_one", "func_two", "func_three"])
    }

    #[test]
    fn test_docs() {
        let item: syn::ItemMod = parse_quote! {
        /// Document for Plugin
        mod plugin {
            #[env_func]
        /// Document for Function
        fn func_one(net: &Network) {
          todo!()
        }
        }
                };

        let mod_doc = get_doc(&item.attrs);
        assert_eq!(mod_doc, "Document for Plugin");

        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
                fn func_two(
            net: &Network,
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let func_doc = get_doc(&item.attrs);
        assert_eq!(func_doc, "Document for Function");
    }

    #[test]
    fn test_valid_env_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
                fn func_name(
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let args = Punctuated::<MetaNameValue, Comma>::new();
        let output = nadi_func_inner(args, item, FuncType::Env).to_string();
        assert!(!output.contains("compile_error!"));
        assert!(output.contains("Document for val"));
        assert!(output.contains("Document for Function"));
    }

    #[test]
    fn test_invalid_env_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
                fn func_two(
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let args: Punctuated<MetaNameValue, Comma> = parse_quote! {
            value = 12
        };
        let output = nadi_func_inner(args, item, FuncType::Env).to_string();
        // compile_error ! ("Argument not in the inner function") ;
        assert!(output.contains("compile_error !"));
    }

    #[test]
    fn test_valid_node_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
            fn func_name(
        node: &NodeInner,
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let args = Punctuated::<MetaNameValue, Comma>::new();
        let output = nadi_func_inner(args, item, FuncType::Node).to_string();
        assert!(!output.contains("compile_error!"));
        assert!(output.contains("Document for val"));
        assert!(output.contains("Document for Function"));
    }

    #[test]
    #[should_panic]
    fn test_invalid_node_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
                fn func_two(
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let args: Punctuated<MetaNameValue, Comma> = parse_quote! {
            val = 12
        };
        // panic!("First argument should be a reference")
        let _ = nadi_func_inner(args, item, FuncType::Node);
    }

    #[test]
    fn test_valid_network_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
            fn func_name(
        network: &Network,
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let args = Punctuated::<MetaNameValue, Comma>::new();
        let output = nadi_func_inner(args, item, FuncType::Network).to_string();
        assert!(!output.contains("compile_error!"));
        assert!(output.contains("Document for val"));
        assert!(output.contains("Document for Function"));
    }

    #[test]
    #[should_panic]
    fn test_invalid_network_func() {
        let item: syn::ItemFn = parse_quote! {
            /// Document for Function
                fn func_two(
            /// Document for val
            val: i64
            ) {
              todo!()
                }
        };
        let args: Punctuated<MetaNameValue, Comma> = parse_quote! {
            val = 12
        };
        // panic!("First argument should be a reference")
        let _ = nadi_func_inner(args, item, FuncType::Network);
    }

    #[test]
    fn test_valid_plugin() {
        let item: syn::ItemMod = parse_quote! {
            mod plug_name{

        /// Document for Function
        #[env_func]
            fn func_name(
        network: &Network,
            /// Document for val
            val: i64
            ) {
              todo!()
            }
        }
        };
        let args = Punctuated::<MetaNameValue, Comma>::new();
        let output = nadi_export_plugin(args.clone(), item.clone(), true).to_string();
        // it doesn't test many things now, I think the best way to
        // test would be to compile the plugin and call it, refer to
        // the tests in cargo package for that type of tests.
        assert!(!output.contains("compile_error!"));
        assert!(output.contains("NadiExternalPlugin"));
        assert!(!output.contains("NadiPlugin"));
        let output = nadi_export_plugin(args, item, false).to_string();
        assert!(!output.contains("compile_error!"));
        assert!(!output.contains("NadiExternalPlugin"));
        assert!(output.contains("NadiPlugin"));
    }
}