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
//! Proc macro for tcl (and tk).

use bind_syn::Bind;

use proc_macro::TokenStream;

use quote::quote;

use syn::{
    Block,
    DeriveInput,
    Expr,
    ExprBlock,
    ExprClosure,
    FnArg,
    GenericParam,
    Generics,
    Ident,
    Item,
    ItemFn,
    Pat,
    PatIdent,
    PatType,
    ReturnType,
    Stmt,
    Token,
    Type,
    parenthesized,
    parse::{self, Parse, ParseStream},
    parse_macro_input,
    parse_quote,
    punctuated::Punctuated,
    token::{Comma, Colon},
    visit_mut::VisitMut,
};

use proc_macro2::Span;

use uuid::Uuid;

struct TclProc;

impl VisitMut for TclProc {
    fn visit_item_fn_mut( &mut self, item_fn: &mut ItemFn ) {
        let argc = item_fn.sig.inputs.len();
        item_fn.sig.abi = Some( parse_quote!( extern "C" ));

        let variadic = item_fn.sig.variadic.take();
        let is_variadic = variadic.is_some();

        let mut inputs: Punctuated<FnArg,Comma> = parse_quote!(
            __client_data: tcl::reexport_clib::ClientData, __tcl_interp: *mut tcl::reexport_clib::Tcl_Interp, __objc: std::os::raw::c_int, __objv: *const *mut tcl::reexport_clib::Tcl_Obj
        );
        if inputs == item_fn.sig.inputs {
            return;
        }
        std::mem::swap( &mut inputs, &mut item_fn.sig.inputs );

        let mut output: ReturnType = parse_quote!( -> std::os::raw::c_int );
        std::mem::swap( &mut output, &mut item_fn.sig.output );

        let mut existing_stmts = Vec::<Stmt>::new();
        std::mem::swap( &mut existing_stmts, &mut item_fn.block.stmts );

        let mut body: Block = parse_quote! {{
            let mut __interp = unsafe{ tcl::Interp::from_raw( __tcl_interp ).unwrap() };
            let __origin_objs: &[*mut tcl::reexport_clib::Tcl_Obj] = unsafe{ std::slice::from_raw_parts( __objv.offset(1), (__objc-1) as usize )};
            if __origin_objs.len() != #argc {
                if __origin_objs.len() < #argc || !#is_variadic {
                    unsafe {
                        tcl::reexport_clib::Tcl_WrongNumArgs( __tcl_interp, 1, __objv, std::ptr::null() );
                        tcl::CodeToResult::code_to_result( tcl::reexport_clib::TCL_ERROR as std::os::raw::c_int, &__interp )?;
                    }
                }
            }
            let mut __objs = __origin_objs[..#argc].to_vec();
            let mut __variadic_args = __origin_objs[#argc..].to_vec();
            use std::convert::TryFrom;

            let mut __ref_objs = std::collections::HashMap::<&'static str, *mut tcl::reexport_clib::Tcl_Obj>::new();

            macro_rules! tcl_invalidate_str_rep {
                ($ident:ident) => {
                    __ref_objs.get( stringify!( $ident )).map( |tcl_obj| unsafe{
                        tcl::reexport_clib::Tcl_InvalidateStringRep( *tcl_obj );
                    });
                };
            }

            macro_rules! tcl_interp { () => { __interp }}
            macro_rules! tcl_variadic_args { () => { __variadic_args }}
        }};

        body.stmts.reserve( argc * 5 + existing_stmts.len() );

        let mut args = Vec::new();
        for (nth, arg) in inputs.iter().enumerate() {
            match arg {
                FnArg::Receiver(_) => panic!("#[proc] does not support method"),
                FnArg::Typed( pat_type ) => {
                    let pat = &*pat_type.pat;
                    args.push( pat.clone() );

                    let ty = &*pat_type.ty;
                    match &*ty {
                        Type::Reference( type_ref ) => match pat {
                            Pat::Ident( pat_ident ) => {
                                body.stmts.push( parse_quote!( unsafe {
                                    let origin_obj = __objs[ #nth ];
                                    __objs[ #nth ] = __interp.get( Obj::from_raw( origin_obj ))?.as_ptr();
                                }));
                                let ident = &pat_ident.ident;
                                body.stmts.push( parse_quote!(
                                    __ref_objs.entry( stringify!( #ident )).or_insert( __objs[ #nth ]);
                                ));

                                let ty_elem = &*type_ref.elem;
                                body.stmts.push( parse_quote!(
                                    let mut __obj = unsafe{ tcl::Obj::from_raw( __objs[ #nth ])};
                                ));
                                body.stmts.push( parse_quote!(
                                    let #ident = tcl::Tcl::<#ty_elem>::ptr_from_obj( __obj )?;
                                ));
                                if type_ref.mutability.is_none() {
                                    body.stmts.push( parse_quote!(
                                        let #ident: #ty = &*unsafe{ #ident.as_ref() }.deref().borrow();
                                    ));
                                } else {
                                    body.stmts.push( parse_quote!(
                                        let #ident: #ty = &mut *unsafe{ #ident.as_ref() }.deref().borrow_mut();
                                    ));
                                }
                            },
                            _ => panic!("#[tcl_proc] argument should be in the form of `ident: Type`"),
                        },
                        _ => {
                            args.push( pat.clone() );

                            body.stmts.push( parse_quote!(
                                let mut __obj = unsafe{ tcl::Obj::from_raw( __objs[ #nth ])};
                            ));
                            body.stmts.push( parse_quote!(
                                //let #pat = tcl::from_obj::<#ty>( &__obj )?;
                                let #pat = <#ty>::try_from( __obj )?;
                            ));
                        },
                    }
                },
            }
        }

        body.stmts.extend( existing_stmts );

        let tcl_inputs = &item_fn.sig.inputs;
        let mut attrs = Vec::new();
        std::mem::swap( &mut attrs, &mut item_fn.attrs );

        let mut new_body: Block = parse_quote! {{
            use tcl::UnwrapOrAbort;

            std::panic::catch_unwind( || {
                let mut __tcl_completion_code: std::os::raw::c_int = tcl::reexport_clib::TCL_OK as std::os::raw::c_int;

                #(#attrs)* fn __tcl_inner_proc( #tcl_inputs ) #output #body

                match __tcl_inner_proc( __client_data, __tcl_interp, __objc, __objv ) {
                    Ok( value ) => unsafe {
                        tcl::reexport_clib::Tcl_SetObjResult( __tcl_interp, Obj::from( value ).into_raw() );
                    },
                    Err( _ ) => __tcl_completion_code = tcl::reexport_clib::TCL_ERROR as std::os::raw::c_int,
                }

                __tcl_completion_code
            })
            .unwrap_or_abort( "Abort process to prevent undefined behaviour on panic across an FFI boundary." )
        }};

        std::mem::swap( &mut *item_fn.block, &mut new_body );
    }

    fn visit_block_mut( &mut self, block: &mut Block ) {
        if block.stmts.len() == 1 {
            let mut ident = None;
            if let Stmt::Item( Item::Fn( item_fn )) = block.stmts.first().unwrap() {
                ident = Some( item_fn.sig.ident.clone() );
            }
            let ident = ident.unwrap();
            block.stmts.push( parse_quote!( #ident ));

            if let Stmt::Item( Item::Fn( item_fn )) = block.stmts.first_mut().unwrap() {
                self.visit_item_fn_mut( item_fn );
                return;
            }
        }
        panic!("#[proc] attribute supports fn and block only");
    }
}

/// A proc macro attribute for filling the gap between `ObjCmdProc` functions and Rust functions with "normal" input arguments.
///
/// # Purpose
///
/// Generally, a Tcl command's function signature is `extern "C" fn( tcl::reexport_clib::ClientData, *mut tcl::reexport_clib::Tcl_Interp, c_int, *const *mut tcl::reexport_clib::Tcl_Obj ) -> c_int`, aka `ObjCmdProc`.
/// Arguments are stored in an array of `tcl::reexport_clib::Tcl_Obj`, and must be converted to real types before using them, which is boring.
///
/// With the help of the `#[proc]` attribute, The translation of function signatures and conversions of arguments are generated behind the proc macros.
///
/// This attributes will generate code to catch panics and abort the program to avoid undefined behaviour caused by panic across FFI boundary.
///
/// # Constraints
///
/// Two category of parameters are allowed:
///
/// - Owned value
///
///   Implementation detail: using `std::convert::TryFrom` to obtain the argument.
///
/// - Borrowed value
///
///   Implementation detail: borrowing from `Tcl<T>` to obtain the argument which borrows `T`.
///
/// The returning type is preferred but not mandatory a `Result<T,E>`:
///
/// - The `Ok` value will be converted to a Tcl `Obj` which is the result for the interpreter.
///
/// - The `Err` value must be able to be converted from the following errors: `InterpError`, `DeError`, `NullDataPtr`.
///
///   If all the errors are from this crate, you can simply use `-> TclResult<T>`.
///
///   If all the errors implement `std::error::Error`, you can simply use `-> Result<T, Box<dyn std::error::Error>>`.
///
///   Otherwise you can use checked exceptions: `#[cex] fn your_command( /* args omitted */ ) -> Result!( T throws InterpError, DeError, NullDataPtr, YourErrors )`.
#[proc_macro_attribute]
pub fn proc( _args: TokenStream, input: TokenStream ) -> TokenStream {
    if let Ok( mut input ) = syn::parse::<ItemFn>( input.clone() ) {
        // #[proc] item_fn
        TclProc.visit_item_fn_mut( &mut input );
        let expanded = quote!{
            #[allow( unused_macros )]
            #input
        };
        expanded.into()
    } else if let Ok( mut input ) = syn::parse::<Block>( input ) {
        // #[proc] { item_fn }
        TclProc.visit_block_mut( &mut input );
        TokenStream::from( quote!{
            #[allow( unused_macros )]
            #input
        })
    } else {
        panic!("tcl_derive::proc supports functions and blocks only.");
    }
}

const BAD_INPUT: &'static str = "tclfn!()/tclosure!()'s closure inputs should be `id` or `id:type`.";

const MIX_UP: &'static str = "Not allowed to mix up event-arguments and non-event-arguments.";

fn set_id_type_pat( pat: &mut Pat, ident: Ident, ty: Type ) {
    *pat = Pat::Type( PatType {
        attrs       : vec![],
        pat         : Box::new( Pat::Ident( PatIdent{
            attrs       : vec![],
            by_ref      : None,
            mutability  : None,
            ident       ,
            subpat      : None, })),
        colon_token : Colon( Span::call_site() ),
        ty          : Box::new( ty ),
    });
}

fn id_of_pat( pat: &Pat ) -> Option<Ident> {
    match pat {
        Pat::Ident( pat_ident ) => Some( pat_ident.ident.clone() ),
        _ => None,
    }
}

fn push_special_id_in_pat_ty( args: &mut String, pat_ty: &PatType ) {
    match id_of_pat( &*pat_ty.pat ) {
        Some( id ) => match tk_event_detail_name_and_type( &id ) {
            Some((name, _)) => args.push_str( name ),
            None => if !args.is_empty() { panic!( "{MIX_UP}" ); }
        }
        None => panic!( "{BAD_INPUT}" ),
    }
}

fn translate_special_fn_args<'a>( args: Option<Expr>, fn_arg: impl Iterator<Item=&'a mut FnArg> ) -> Expr {
    args.unwrap_or_else( || {
        let mut args = String::new();
        for arg in fn_arg {
            match arg {
                FnArg::Receiver(_) => panic!(),
                FnArg::Typed( pat_ty ) => push_special_id_in_pat_ty( &mut args, pat_ty ),
            }
        }
        parse_quote!( #args )
    })
}

fn callback_fn( interp: Expr, cmd: Option<Expr>, args: Option<Expr>, mut item_fn: ItemFn ) -> TokenStream {
    let ident = &item_fn.sig.ident;
    let inputs = &mut item_fn.sig.inputs;

    let cmd = cmd.unwrap_or_else( || parse_quote!{ stringify!( #ident )});
    let args = translate_special_fn_args( args, inputs.iter_mut() );

    let mut default_values = Vec::<>::with_capacity( inputs.len() );
    for arg in inputs.iter().rev() {
        if let FnArg::Typed( pat_type ) = arg {
            let default_value =
                (*pat_type).attrs.iter().find_map( |attr| {
                    if let syn::Meta::List( meta_list ) = &attr.meta {
                        let segments = &meta_list.path.segments;
                        if segments.len() == 1 && segments.first().unwrap().ident == "default" {
                            return Some( meta_list.tokens.clone() );
                        }
                    }
                    None
                })
            ;
            match default_value {
                Some( value ) => {
                    default_values.push( value );
                },
                None => break,
            }
        }
    }

    let expanded = if default_values.is_empty() {
        quote! {{
            #[tcl::proc]
            #[allow( unused_macros )]
            #item_fn

            let cmd = #cmd;
            unsafe{ (#interp).def_proc( cmd, #ident ); }
            format!( "{} {}", cmd, #args )
        }}
    } else {
        let argc = inputs.len();
        let optional_argc = default_values.len();
        let required_argc = argc - optional_argc;

        let param_list = format!( "{}{}",
            (0..required_argc   ).fold( String::new(), |acc,n|
                format!( "{acc} arg{n}" )),
            (required_argc..argc).fold( String::new(), |acc,n|
                format!( "{acc} {{ arg{n} {} }}", default_values[ n-required_argc ])),
        );
        let params = (0..argc).fold( String::new(), |acc,n| format!( "{acc} $arg{n}" ));

        let uuid = make_ident( &format!( "__tcl_fn_inner_{}", Uuid::new_v4().simple() ));
        let name: Expr = parse_quote!{ &format!( "{}", stringify!( #uuid ))};

        quote! {{
            #[tcl::proc]
            #[allow( unused_macros )]
            #item_fn

            let cmd = #cmd;
            unsafe {
                (#interp).def_proc( #name, #ident );

                (#interp).run(
                    format!( "proc {} {{ {} }} {{ {} {} }}", cmd, #param_list, #name, #params )
                ).ok();
            }

            format!( "{} {}", cmd, #args )
        }}
    };

    expanded.into()
}

/// Helps to register rust functions as Tcl commands, or Tk event callbacks.
///
/// # Syntax
///
/// `tclfn!( interp, cmd, args, func )`
///
/// # Input parameters
///
/// 1. interp, the Tcl interpreter instance.
///
/// 2. cmd, the name of the command being registered in Tcl. Optional.
///
/// 3. args, the arguments provided in Tcl on executing the command. Optional.
/// You can provide `args` if you don't want this macro to interpret `evt_*`/`vldt_*` arguments as Tk event callback arguments.
///
/// 4. func, the function defined in Rust.
///   Note: an attribute `#[default(value)]` on an parameter will assign a default `value` for this parameter.
///
/// Without `args` given, some special arguments starting with `evt_` or `vldt_` will be treated as predefined Tk event
/// callback arguments. The annotated types can be substituted by different types.
///
/// See `tclosure!()`'s doc comments for more.
///
/// # Output
///
/// Returns a `String` of the command name.
///
/// # Example
///
/// ```rust,no_run
///
/// use tcl::*;
///
/// let interpreter = Interpreter::new()?;
///
/// let cmd = tclfn!( &interpreter, /*cmd: "mul", args: "",*/
///     fn mul( a: i32, b: i32 ) -> TclResult<i32> { Ok( a * b )}
/// );
///
/// let c = interpreter.eval( "mul 3 7" )?;
/// assert_eq!( c.as_i32(), 21 );
/// ```
#[proc_macro]
pub fn tclfn( input: TokenStream ) -> TokenStream {
    struct TclFn {
        interp : Expr,
        cmd    : Option<Expr>,
        args   : Option<Expr>,
        func   : ItemFn,
    }

    impl Parse for TclFn {
        fn parse( input: ParseStream ) -> parse::Result<Self> {
            let interp = input.parse::<Expr>()?;
            input.parse::<Token![,]>()?;

            let (mut cmd, mut args) = (None, None);
            while !input.is_empty() && input.peek( Ident ) {
                match input.parse::<Ident>()?.to_string().as_str() {
                    "cmd"  => {
                        input.parse::<Token![:]>()?;
                        cmd = Some( input.parse::<Expr>()? );
                    },
                    "args" => {
                        input.parse::<Token![:]>()?;
                        args = Some( input.parse::<Expr>()? );
                    },
                    _ => panic!( "unsupported named arguments of tclfn!(), should be `cmd` or `args`."),
                }
                input.parse::<Token![,]>()?;
            }

            let func = input.parse::<ItemFn>()?;
            Ok( TclFn{ interp, cmd, args, func })
        }
    }

    let TclFn{ interp, cmd, args, func } = parse_macro_input!( input as TclFn );
    callback_fn( interp, cmd, args, func )
}

fn translate_special_closure_args<'a>( args: Option<Expr>, pats: impl Iterator<Item=&'a mut Pat> ) -> Expr {
    args.unwrap_or_else( || {
        let mut args = String::new();
        for pat in pats {
            match pat {
                Pat::Type( pat_ty ) => push_special_id_in_pat_ty( &mut args, pat_ty ),
                Pat::Ident( pat_ident ) => {
                    let ident = pat_ident.ident.clone();
                    match tk_event_detail_name_and_type( &ident ) {
                        Some((name, ty)) => {
                            args.push_str( name );
                            set_id_type_pat( pat, ident, ty );
                        }
                        None => if !args.is_empty() { panic!( "{MIX_UP}" ); }
                    }
                }
                _ => panic!( "{BAD_INPUT}" ),
            }
        }
        parse_quote!( #args )
    })
}

struct TclosureInput {
    interp  : Expr,
    cmd     : Option<Expr>,
    args    : Option<Expr>,
    bind    : Option<Punctuated<Bind,Token![,]>>,
    closure : ExprClosure,
}

impl Parse for TclosureInput {
    fn parse( input: ParseStream ) -> parse::Result<Self> {
        let interp = input.parse::<Expr>()?;
        input.parse::<Token![,]>()?;

        let (mut cmd, mut args, mut bind) = (None, None, None);
        while !input.is_empty() && input.peek( Ident ) {
            match input.parse::<Ident>()?.to_string().as_str() {
                "cmd"  => {
                    input.parse::<Token![:]>()?;
                    cmd = Some( input.parse::<Expr>()? );
                }
                "args" => {
                    input.parse::<Token![:]>()?;
                    args = Some( input.parse::<Expr>()? );
                }
                "bind" => {
                    input.parse::<Token![:]>()?;
                    let content;
                    parenthesized!( content in input );
                    bind = Some( Punctuated::parse_terminated( &content )? );
                }
                _ => panic!( "unsupported named arguments of tclosure!(), should be `cmd`, `args` or `bind`."),
            }
            input.parse::<Token![,]>()?;
        }

        let closure = input.parse::<ExprClosure>()?;

        Ok( TclosureInput{ interp, cmd, args, bind, closure })
    }
}

fn tk_event_detail_name_and_type( id: &Ident ) -> Option<(&'static str, Type)> {
    match id.to_string().as_str() {
        "evt_serial"         => Some((" %#", parse_quote!( std::ffi::c_int         ))),
        "evt_above"          => Some((" %a", parse_quote!( std::ffi::c_int         ))),
        "evt_button"         => Some((" %b", parse_quote!( tk::event::ButtonNo     ))),
        "evt_count"          => Some((" %c", parse_quote!( std::ffi::c_int         ))),
        "evt_detail"         => Some((" %d", parse_quote!( tcl::Obj                ))),
        "evt_focus"          => Some((" %f", parse_quote!( bool                    ))),
        "evt_height"         => Some((" %h", parse_quote!( std::ffi::c_int         ))),
        "evt_window"         => Some((" %i", parse_quote!( std::ffi::c_int         ))),
        "evt_keycode"        => Some((" %k", parse_quote!( std::ffi::c_int         ))),
        "evt_mode"           => Some((" %m", parse_quote!( tk::event::TkNotifyMode ))),
        "evt_override"       => Some((" %o", parse_quote!( bool                    ))),
        "evt_place"          => Some((" %p", parse_quote!( tk::event::TkPlaceOn    ))),
        "evt_state"          => Some((" %s", parse_quote!( String                  ))),
        "evt_time"           => Some((" %t", parse_quote!( std::ffi::c_int         ))),
        "evt_width"          => Some((" %w", parse_quote!( std::ffi::c_int         ))),
        "evt_x"              => Some((" %x", parse_quote!( std::ffi::c_int         ))),
        "evt_y"              => Some((" %y", parse_quote!( std::ffi::c_int         ))),
        "evt_unicode"        => Some((" %A", parse_quote!( char                    ))),
        "evt_borderwidth"    => Some((" %B", parse_quote!( std::ffi::c_int         ))),
        "evt_delta"          => Some((" %D", parse_quote!( std::ffi::c_int         ))),
        "evt_sendevent"      => Some((" %E", parse_quote!( bool                    ))),
        "evt_keysym"         => Some((" %K", parse_quote!( char                    ))),
        "evt_matches"        => Some((" %M", parse_quote!( std::ffi::c_int         ))),
        "evt_keysym_decimal" => Some((" %N", parse_quote!( std::ffi::c_int         ))),
        "evt_key"            => Some((" %N", parse_quote!( tk::TkKey               ))),
        "evt_property"       => Some((" %P", parse_quote!( String                  ))),
        "evt_root"           => Some((" %R", parse_quote!( std::ffi::c_int         ))),
        "evt_subwindow"      => Some((" %S", parse_quote!( std::ffi::c_int         ))),
        "evt_type"           => Some((" %T", parse_quote!( tk::event::TkEventType  ))),
        "evt_window_path"    => Some((" %W", parse_quote!( String                  ))),
        "evt_rootx"          => Some((" %X", parse_quote!( std::ffi::c_int         ))),
        "evt_rooty"          => Some((" %Y", parse_quote!( std::ffi::c_int         ))),
        "vldt_action"        => Some((" %d", parse_quote!( tk::event::TkValidatingAction ))),
        "vldt_index"         => Some((" %i", parse_quote!( std::ffi::c_int               ))),
        "vldt_new"           => Some((" %P", parse_quote!( String                        ))),
        "vldt_old"           => Some((" %s", parse_quote!( String                        ))),
        "vldt_text"          => Some((" %S", parse_quote!( String                        ))),
        "vldt_set"           => Some((" %v", parse_quote!( tk::event::TkValidationSet    ))),
        "vldt_op"            => Some((" %V", parse_quote!( tk::event::TkValidationOp     ))),
        "vldt_name"          => Some((" %W", parse_quote!( String                        ))),
        _ => None,
    }
}

/// Helps to register rust closures as Tcl commands or Tk event callbacks.
///
/// # Syntax
///
/// `tclosure!( interp, cmd, args, bind, closure )`
///
/// or more precisely:
///
/// `tclosure!( $interp:expr, cmd:$cmd:expr, args:$args:expr, bind:($($bind: bind_syn::Bind),*), $closure:expr )`
///
/// # Input parameters
///
/// 1. interp, the Tcl interpreter instance.
///
/// 2. cmd, the name of the command being registered in Tcl. Optional. Note: be careful to keep multple closures from sharing
/// the same `cmd` name.
///
/// 3. args, the arguments provided in Tcl on executing the command. Optional.
/// You can provide `args` if you don't want this macro to interpret `evt_*`/`vldt_*` arguments as Tk event callback arguments.
///
/// 4. bind list, for cloning data into the closure, which is similar inside `bind::bind!()`. Optional.
///
/// 5. closure, the closure defined in Rust. Its capture must be `move` and `move` keywords could be omitted.
///   Note: an attribute `#[default(value)]` on a parameter will assign a default `value` for this parameter.
///
/// Without `args` given, some special arguments starting with `evt_` or `vldt_` will be treated as predefined Tk event
/// callback arguments. The annotated types can be omitted or substituted by different types.
///
/// ## Tk Event details
///
/// * evt_serial: c_int
///
/// The number of the last client request processed by the server (the serial field from the event). Valid for all event types.
///
/// * evt_above: c_int
///
/// The above field from the event, formatted as a hexadecimal number. Valid only for Configure events. Indicates the sibling
/// window immediately below the receiving window in the stacking order, or 0 if the receiving window is at the bottom.
///
/// * evt_button: tk::event::ButtonNo
///
/// The number of the button that was pressed or released. Valid only for ButtonPress and ButtonRelease events.
///
/// * evt_count: c_int
///
/// The count field from the event. Valid only for Expose events. Indicates that there are count pending Expose events which
/// have not yet been delivered to the window.
///
/// * evt_detail: Obj
///
/// The detail or user_data field from the event.
///
/// * evt_focus: bool
///
/// The focus field from the event (false or true). Valid only for Enter and Leave events, true if the receiving window is the
/// focus window or a descendant of the focus window, false otherwise.
///
/// * evt_height: c_int
///
/// The height field from the event. Valid for the Configure, ConfigureRequest, Create, ResizeRequest, and Expose events.
/// Indicates the new or requested height of the window.
///
/// * evt_window: c_int
///
/// The window field from the event, represented as a hexadecimal integer. Valid for all event types.
///
/// * evt_keycode: c_int
///
/// The keycode field from the event. Valid only for KeyPress and KeyRelease events.
///
/// * evt_mode: tk::event::TkNotifyMode
///
/// The mode field from the event. Valid only for Enter, FocusIn, FocusOut, and Leave events.
///
/// * evt_override: bool
///
/// The override_redirect field from the event. Valid only for Map, Reparent, and Configure events.
///
/// * evt_place: tk::event::TkPlaceOn
///
/// The place field from the event, substituted as one of the strings PlaceOnTop or PlaceOnBottom. Valid only for Circulate and
/// CirculateRequest events.
///
/// * evt_state: String
///
/// The state field from the event. For ButtonPress, ButtonRelease, Enter, KeyPress, KeyRelease, Leave, and Motion events, a
/// decimal string is substituted. For Visibility, one of the strings VisibilityUnobscured, VisibilityPartiallyObscured, and
/// VisibilityFullyObscured is substituted. For Property events, substituted with either the string NewValue (indicating that
/// the property has been created or modified) or Delete (indicating that the property has been removed).
///
/// * evt_time: c_int
///
/// The time field from the event. This is the X server timestamp (typically the time since the last server reset) in
/// milliseconds, when the event occurred. Valid for most events.
///
/// * evt_width: c_int
///
/// The width field from the event. Indicates the new or requested width of the window. Valid only for Configure,
/// ConfigureRequest, Create, ResizeRequest, and Expose events.
///
/// * evt_x: c_int, evt_y: c_int
///
/// The x and y fields from the event. For ButtonPress, ButtonRelease, Motion, KeyPress, KeyRelease, and MouseWheel events,
/// evt_x and evt_y indicate the position of the mouse pointer relative to the receiving window. For key events on the Macintosh
/// these are the coordinates of the mouse at the moment when an X11 KeyEvent is sent to Tk, which could be slightly later than
/// the time of the physical press or release. For Enter and Leave events, the position where the mouse pointer crossed the
/// window, relative to the receiving window. For Configure and Create requests, the x and y coordinates of the window relative
/// to its parent window.
///
/// * evt_unicode: char
///
/// Substitutes the UNICODE character corresponding to the event, or the empty string if the event does not correspond to a
/// UNICODE character (e.g. the shift key was pressed). On X11, XmbLookupString (or XLookupString when input method support is
/// turned off) does all the work of translating from the event to a UNICODE character. On X11, valid only for KeyPress event.
/// On Windows and macOS/aqua, valid only for KeyPress and KeyRelease events.
///
/// * evt_borderwidth: c_int
///
/// The border_width field from the event. Valid only for Configure, ConfigureRequest, and Create events.
///
/// * evt_delta: c_int
///
/// This reports the delta value of a MouseWheel event. The delta value represents the rotation units the mouse wheel has been
/// moved. The sign of the value represents the direction the mouse wheel was scrolled.
///
/// * evt_sendevent: bool
///
/// The send_event field from the event. Valid for all event types, false indicates that this is a “normal” event, true
/// indicates that it is a “synthetic” event generated by SendEvent.
///
/// * evt_keysym: char
///
/// The keysym corresponding to the event, as a textual `char`. Valid only for KeyPress and KeyRelease events.
///
/// * evt_matches: c_int
///
/// The number of script-based binding patterns matched so far for the event. Valid for all event types.
///
/// * evt_keysym_decimal: c_int
///
/// The keysym corresponding to the event, substituted as a number. Valid only for KeyPress and KeyRelease events.
///
/// * evt_property: String
///
/// The name of the property being updated or deleted (which may be converted to an XAtom using winfo atom.) Valid only for
/// Property events.
///
/// * evt_root: c_int
///
/// The root window identifier from the event. Valid only for events containing a root field.
///
/// * evt_subwindow: c_int
///
/// The subwindow window identifier from the event, formatted as a hexadecimal number. Valid only for events containing a
/// subwindow field.
///
/// * evt_type: tk::event::TkEventType
///
/// The type field from the event. Valid for all event types.
///
/// * evt_window_path: String
///
/// The path name of the window to which the event was reported (the window field from the event). Valid for all event types.
///
/// * evt_rootx: c_int, evt_rooty: c_int
///
/// The x_root and y_root fields from the event. If a virtual-root window manager is being used then the substituted values are
/// the corresponding x-coordinate and y-coordinate in the virtual root. Valid only for ButtonPress, ButtonRelease, Enter,
/// KeyPress, KeyRelease, Leave and Motion events. Same meaning as evt_x and evt_y, except relative to the (virtual) root
/// window.
///
/// ## Validation details
///
/// * vldt_action: tk::event::TkValidatingAction
///
/// Type of action.
///
/// * vldt_index: c_int
///
/// Index of char string to be inserted/deleted, if any, otherwise -1.
///
/// * vldt_new: String
///
/// The value of the entry if the edit is allowed. If you are configuring the entry widget to have a new textvariable, this
/// will be the value of that textvariable.
///
/// * vldt_old: String
///
/// The current value of entry prior to editing.
///
/// * vldt_text: String
///
/// The text string being inserted/deleted.
///
/// * vldt_set: tk::event::TkValidationSet
///
/// The type of validation currently set.
///
/// * vldt_op:  tk::event::TkValidationOp
///
/// The type of validation that triggered the callback (key, focusin, focusout, forced).
///
/// * vldt_name: String
///
/// The name of the entry widget.
///
/// # Output
///
/// Returns a `String` of the command name.
///
/// # Example, Tk Event callback
///
/// ```rust,no_run
/// widget.bind( button_press_2(),
///     tclosure!( tk, |evt_x, evt_y| tk.popup( menu, evt_x, evt_y, None ))
/// )?;
/// ```
///
/// # Example, Poll
///
/// ```rust,no_run
/// tk.run( tclosure!( tk, cmd:"poll" || {
///     {/* poll and do lots of work, omitted */}
///     tk.after( 100, ("poll",) )?;
///     Ok(())
/// }))?;
/// ```
#[proc_macro]
pub fn tclosure( input: TokenStream ) -> TokenStream {
    let TclosureInput{ interp, cmd, args, bind, mut closure } = parse_macro_input!( input as TclosureInput );
    let bind = bind.unwrap_or_default();
    let bind = bind.iter();

    let output = match &closure.output {
        ReturnType::Default => parse_quote!( Result<(), tk::error::InterpError> ),
        ReturnType::Type( _, ty ) => ty.clone(),
    };

    let attrs = closure.attrs;
    let argc = closure.inputs.len();

    let is_variadic = closure.inputs
        .last_mut()
        .map( |pat| if let Pat::Rest(_) = pat {true} else {false} )
        .unwrap_or( false );
    if is_variadic {
        closure.inputs.pop();
    }
    let non_variadic_argc = if is_variadic { argc-1 } else { argc };

    let args = translate_special_closure_args( args, closure.inputs.iter_mut() );

    let body = &*closure.body;
    let expr_block: ExprBlock = if let Expr::Block( block ) = body {
        block.clone()
    } else {
        parse_quote!{{ #body }}
    };

    let existing_stmts = expr_block.block.stmts;

    let mut body: Block = parse_quote! {{
        let mut __interp = unsafe{ tcl::Interp::from_raw( __tcl_interp ).unwrap() };
        let __origin_objs: &[*mut tcl::reexport_clib::Tcl_Obj] = unsafe{ std::slice::from_raw_parts( __objv.offset(1), (__objc-1) as usize )};

        if __origin_objs.len() != #argc {
            if __origin_objs.len() < #argc || !#is_variadic {
                unsafe {
                    tcl::reexport_clib::Tcl_WrongNumArgs( __tcl_interp, 1, __objv, std::ptr::null() );
                    use tcl::CodeToResult;
                    tcl::CodeToResult::code_to_result( tcl::reexport_clib::TCL_ERROR as std::os::raw::c_int, &__interp )?;
                }
            }
        }

        let mut __objs = __origin_objs[..#non_variadic_argc].to_vec();
        let mut __variadic_args = __origin_objs[#non_variadic_argc..]
            .iter().map( |obj_ptr| unsafe{ Obj::from_raw( *obj_ptr )}).collect::<Vec<Obj>>();
        use std::convert::TryFrom;

        let mut __ref_objs = std::collections::HashMap::<&'static str, *mut tcl::reexport_clib::Tcl_Obj>::new();

        macro_rules! tcl_invalidate_str_rep {
            ($ident:ident) => {
                __ref_objs.get( stringify!( $ident )).map( |tcl_obj| unsafe{
                    tcl::reexport_clib::Tcl_InvalidateStringRep( *tcl_obj );
                });
            };
        }

        macro_rules! tcl_interp { () => { __interp }}
        macro_rules! tcl_va_args { () => { __variadic_args }}
    }};

    body.stmts.reserve( argc * 5 + existing_stmts.len() );
    let mut default_values = Vec::<>::with_capacity( closure.inputs.len() );
    for (nth, arg) in closure.inputs.iter().enumerate() {
        match arg {
            Pat::Type( pat_type ) => {
                let pat = &*pat_type.pat;
                let ty = &*pat_type.ty;
                let default_value =
                    (*pat_type).attrs.iter().find_map( |attr| {
                        if let syn::Meta::List( meta_list ) = &attr.meta {
                            let segments = &meta_list.path.segments;
                            if segments.len() == 1 && segments.first().unwrap().ident == "default" {
                                return Some( meta_list.tokens.clone() );
                            }
                        }
                        None
                    })
                ;
                match default_value {
                    Some( value ) => default_values.push( value ),
                    None => default_values.clear(),
                }
                match &*ty {
                    Type::Reference( type_ref ) => match pat {
                        Pat::Ident( pat_ident ) => {
                            body.stmts.push( parse_quote!( unsafe {
                                let origin_obj = __objs[ #nth ];
                                __objs[ #nth ] = __interp.get( Obj::from_raw( origin_obj ))?.as_ptr();
                            }));
                            let ident = &pat_ident.ident;
                            body.stmts.push( parse_quote!(
                                __ref_objs.entry( stringify!( #ident )).or_insert( __objs[ #nth ]);
                            ));

                            let ty_elem = &*type_ref.elem;
                            body.stmts.push( parse_quote!(
                                let mut __obj = unsafe{ tcl::Obj::from_raw( __objs[ #nth ])};
                            ));
                            body.stmts.push( parse_quote!(
                                let #ident = tcl::Tcl::<#ty_elem>::ptr_from( __obj )?;
                            ));
                            if type_ref.mutability.is_none() {
                                body.stmts.push( parse_quote!(
                                    let #ident: #ty = &*unsafe{ #ident.as_ref() }.deref().borrow();
                                ));
                            } else {
                                body.stmts.push( parse_quote!(
                                    let #ident: #ty = &mut *unsafe{ #ident.as_ref() }.deref().borrow_mut();
                                ));
                            }
                        },
                        _ => panic!("#[tcl_proc] argument should be in the form of `ident: Type`"),
                    },
                    _ => {
                        body.stmts.push( parse_quote!(
                            let mut __obj = unsafe{ tcl::Obj::from_raw( __objs[ #nth ])};
                        ));
                        body.stmts.push( parse_quote!(
                            let #pat = <#ty>::try_from( __obj )?;
                        ));
                    },
                }
            },
            _ => panic!("#[tcl_proc] argument should be in the form of `ident: Type`"),
        }
    }

    body.stmts.extend( existing_stmts );

    let uuid = make_ident( &format!( "__tcl_closure_wrapper_{}", Uuid::new_v4().simple() ));

    let (cmd, random_value) = if cmd.is_some() {
        (cmd.unwrap(), 0_u64)
    } else {
        (parse_quote!(""), Uuid::new_v4().as_u64_pair().1)
    };

    let proc_definition: Vec<Stmt> = if default_values.is_empty() {
        parse_quote!{
             (#interp).def_proc_with_client_data( cmd.as_str(), #uuid, client_data, Some( __deleter ));
        }
    } else {
        let name: Expr = parse_quote!{ &format!( "__tcl_fn_{}", stringify!( #uuid ))};

        let optional_argc = default_values.len();
        let required_argc = argc - optional_argc;

        let param_list = format!( "{}{}",
            (0..required_argc   ).fold( String::new(), |acc,n|
                format!( "{acc} arg{n}" )),
            (required_argc..argc).fold( String::new(), |acc,n|
                format!( "{acc} {{ arg{n} {} }}", default_values[ n-required_argc ])),
        );
        let params = (0..argc).fold( String::new(), |acc,n| format!( "{acc} $arg{n}" ));

        parse_quote!{
            (#interp).def_proc_with_client_data( #name, #uuid, client_data, Some( __deleter ));
            (#interp).run(
                format!( "proc {} {{ {} }} {{ {} {} }}", cmd, #param_list, #name, #params )
            ).ok();
        }
    };

    let expanded = quote!{{
        #(#bind)*

        extern "C" fn #uuid( __client_data: tcl::reexport_clib::ClientData, __tcl_interp: *mut tcl::reexport_clib::Tcl_Interp, __objc: std::os::raw::c_int, __objv: *const *mut tcl::reexport_clib::Tcl_Obj ) -> std::os::raw::c_int {
            let closure: &mut Box<dyn Fn( tcl::reexport_clib::ClientData, *mut tcl::reexport_clib::Tcl_Interp, std::os::raw::c_int, *const *mut tcl::reexport_clib::Tcl_Obj )->#output> = unsafe{ &mut *( __client_data as *mut _ )};
            match closure( std::ptr::null_mut(), __tcl_interp, __objc, __objv ) {
                Ok( value ) => {
                    unsafe{ tcl::reexport_clib::Tcl_SetObjResult( __tcl_interp, Obj::from( value ).into_raw() )};
                    tcl::reexport_clib::TCL_OK as std::os::raw::c_int
                },
                Err( _ ) => tcl::reexport_clib::TCL_ERROR as std::os::raw::c_int,
            }
        }

        extern "C" fn __deleter( __client_data: tcl::reexport_clib::ClientData ) {
            let _: Box<Box<dyn Fn( tcl::reexport_clib::ClientData, *mut tcl::reexport_clib::Tcl_Interp, std::os::raw::c_int, *const *mut tcl::reexport_clib::Tcl_Obj )->#output>> = unsafe{ Box::from_raw( __client_data as *mut _ )};
        }

        fn __box_new_static_closure<F>( f: F ) -> Box<F>
            where F: 'static + Fn( tcl::reexport_clib::ClientData, *mut tcl::reexport_clib::Tcl_Interp, std::os::raw::c_int, *const *mut tcl::reexport_clib::Tcl_Obj ) -> #output
        {
            Box::new( f )
        }

        let closure: Box<Box<dyn Fn( tcl::reexport_clib::ClientData, *mut tcl::reexport_clib::Tcl_Interp, std::os::raw::c_int, *const *mut tcl::reexport_clib::Tcl_Obj )->#output>> = Box::new( __box_new_static_closure(
            #(#attrs)*
            #[allow( unused_macros )]
            move |__client_data: tcl::reexport_clib::ClientData, __tcl_interp: *mut tcl::reexport_clib::Tcl_Interp, __objc: std::os::raw::c_int, __objv: *const *mut tcl::reexport_clib::Tcl_Obj| -> #output #body
        ));

        let client_data = Box::into_raw( closure ) as tcl::reexport_clib::ClientData;

        let address_as_name = format!( "__tclosure_{:?}", #random_value.wrapping_add( client_data as u64 ));

        let cmd = if (#cmd).is_empty() {
            address_as_name
        } else {
            String::from( #cmd )
        };

        unsafe{ #(#proc_definition)* }

        format!( "{} {}", cmd, #args )
    }};

    expanded.into()
}

/// Derives `std::from::TryFrom<tcl::Obj>`, based on `serde::Deserialize`.
#[proc_macro_derive( TryFromDe )]
pub fn derive_try_from_de( input: TokenStream ) -> TokenStream {
    let derive_input = parse_macro_input!( input as DeriveInput );
    let name = derive_input.ident;
    let generics = add_trait_bounds( derive_input.generics );
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
    let expanded = quote! {
        impl #impl_generics std::convert::TryFrom<Obj> for #name #ty_generics #where_clause {
            type Error = tcl::error::DeError;

            fn try_from( obj: Obj ) -> Result<Self, Self::Error> {
                from_obj( obj )
            }
        }
    };
    expanded.into()
}

fn add_trait_bounds( mut generics: Generics ) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type( ref mut type_param ) = *param {
            let bound = syn::parse_str( "serde::Deserialize" ).unwrap();
            type_param.bounds.push( bound );
        }
    }
    generics
}

fn make_ident( sym: &str ) -> Ident {
    Ident::new( sym, Span::call_site() )
}