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



//! # Intro
//!
//! This document covers the usage of the crate's macros, it does 
//! not delve into the detailed logic of the generated code.
//! 
//! For a comprehensive understanding of the underlying
//! concepts and implementation details of the Actor Model,  
//! it's recommended to read the article  [Actors with Tokio](https://ryhl.io/blog/actors-with-tokio/)
//! by Alice Ryhl ( also known as _Darksonn_ ) also a great 
//! talk by the same author on the same subject if a more 
//! interactive explanation is prefered 
//! [Actors with Tokio – a lesson in ownership - Alice Ryhl](https://www.youtube.com/watch?v=fTXuGRP1ee4)
//! (video).
//! This article not only inspired the development of the 
//! `interthread` crate but also serves as foundation 
//! for the Actor Model implementation logic in it. 


//! ## What is an Actor ?
//!
//! Despite being a fundamental concept in concurrent programming,
//! defining exactly what an actor is can be ambiguous.
//! 
//! - *Carl Hewitt*, often regarded as the father of the Actor Model,
//! [The Actor Model](https://www.youtube.com/watch?v=7erJ1DV_Tlo) (video).
//! 
//! - Wikipidia [Actor Model](https://en.wikipedia.org/wiki/Actor_model)
//!  
//!
//! a quote from [Actors with Tokio](https://ryhl.io/blog/actors-with-tokio/):
//! 
//! > "The basic idea behind an actor is to spawn a 
//! self-contained task that performs some job independently
//! of other parts of the program. Typically these actors
//! communicate with the rest of the program through 
//! the use of message passing channels. Since each actor 
//! runs independently, programs designed using them are 
//! naturally parallel."
//! > - Alice Ryhl 
//!
//! ## What is the problem ?
//! 
//! To achieve parallel execution of individual objects 
//! within the same program, it is challenging due 
//! to the need for various types that are capable of 
//! working across threads. The main difficulty 
//! lies in the fact that as you introduce thread-related types,
//! you can quickly lose sight of the main program 
//! idea as the focus shifts to managing thread-related 
//! concerns.
//!
//! It involves using constructs like threads, locks, channels,
//! and other synchronization primitives. These additional 
//! types and mechanisms introduce complexity and can obscure 
//! the core logic of the program.
//! 
//! 
//! Moreover, existing libraries like [`actix`](https://docs.rs/actix/latest/actix/), [`axiom`](https://docs.rs/axiom/latest/axiom/), 
//! designed to simplify working within the Actor Model,
//! often employ specific concepts, vocabulary, traits and types that may
//! be unfamiliar to users who are less experienced with 
//! asynchronous programming and futures. 
//! 
//! ## Solution 
//! 
//! The [`actor`](./attr.actor.html) macro -  when applied to the 
//! implementation block of a given "MyActor" object,
//! generates additional types and functions 
//! that enable communication between threads.
//! 
//! A notable outcome of applying this macro is the 
//! creation of the `MyActorLive` struct ("ActorName" + "Live"),
//! which acts as an interface/handle to the `MyActor` object.
//! `MyActorLive` retains the exact same public method signatures
//! as `MyActor`, allowing users to interact with the actor as if 
//! they were directly working with the original object.
//! 
//! ### Examples
//! 
//! 
//! Filename: Cargo.toml
//! 
//!```text
//!interthread = "0.1.8"
//!oneshot     = "0.1.5" 
//!```
//! 
//! Filename: main.rs
//!```rust
//!pub struct MyActor {
//!    value: i8,
//!}
//!
//!#[interthread::actor(channel=2)] // <-  this is it 
//!impl MyActor {
//!
//!    pub fn new( v: i8 ) -> Self {
//!       Self { value: v } 
//!    }
//!    pub fn increment(&mut self) {
//!        self.value += 1;
//!    }
//!    pub fn add_number(&mut self, num: i8) -> i8 {
//!        self.value += num;
//!        self.value
//!    }
//!    pub fn get_value(&self) -> i8 {
//!        self.value
//!    }
//!}
//! // uncomment to see the generated code
//! //#[interthread::example(file="src/main.rs")]  
//!fn main() {
//!
//!    let actor = MyActorLive::new(5);
//!
//!    let mut actor_a = actor.clone();
//!    let mut actor_b = actor.clone();
//!
//!    let handle_a = std::thread::spawn( move || { 
//!    actor_a.increment();
//!    });
//!
//!    let handle_b = std::thread::spawn( move || {
//!    actor_b.add_number(5);
//!    });
//!
//!    let _ = handle_a.join();
//!    let _ = handle_b.join();
//!
//!    assert_eq!(actor.get_value(), 11)
//!}
//!
//! ```
//! 
//! An essential point to highlight is that when invoking 
//! `MyActorLive::new`, not only does it return an instance 
//! of `MyActorLive`, but it also spawns a new thread that 
//! contains an instance of `MyActor` in it. 
//! This introduces parallelism to the program.
//! 
//! The code generated by the [`actor`](./attr.actor.html) takes 
//! care of the underlying message routing and synchronization, 
//! allowing developers to rapidly prototype their application's
//! core functionality. This fast sketching capability is
//! particularly useful when exploring different design options, 
//! experimenting with concurrency models, or implementing 
//! proof-of-concept systems. Not to mention, the cases where 
//! the importance of the program lies in the result of its work 
//! rather than its execution.
//!
//! 
//! # SDPL Framework
//! 
//! 
//!  The code generated by the [`actor`](./attr.actor.html) macro 
//! can be divided into four more or less important but distinct 
//! parts: [`script`](#script) ,[`direct`](#direct), 
//! [`play`](#play), [`live`](#live) .
//! 
//!  This categorization provides an intuitive 
//! and memorable way to understand the different aspects 
//! of the generated code.
//! 
//! Expanding the above example, uncomment the [`example`](./attr.example.html)
//! placed above the `main` function, go to `examples/inter/main.rs` in your 
//! root directory and find `MyActor` along with additional SDPL parts :
//! 
//! # `script`
//! 
//!  Think of script as a message type definition.
//! 
//!  The declaration of an `ActorName + Script` enum, which is 
//! serving as a collection of variants that represent 
//! different messages that may be sent across threads through a
//! channel. 
//! 
//!  Each variant corresponds to a struct with fields
//! that capture the input and/or output parameters of 
//! the respective public methods of the Actor.
//!  
//! 
//! ```rust
//! 
//!#[derive(Debug)]
//!pub enum MyActorScript {
//!    Increment {},
//!    AddNumber {
//!        input: (i8),
//!        output: oneshot::Sender<i8>,
//!    },
//!    GetValue {
//!        output: oneshot::Sender<i8>,
//!    },
//!}
//! 
//! ```
//! 
//! > **Note**: Method `new` not included as a variant in the `script`. 
//! 
//! 
//! # direct
//! The implementation block of [`script`](#script), specifically 
//! the `actor_name_ + direct` method which allows 
//! for direct invocation of the Actor's methods by mapping 
//! the enum variants to the corresponding function calls.
//! 
//! 
//! ```rust
//!impl MyActorScript {
//!    pub fn my_actor_direct(self, actor: &mut MyActor) {
//!        match self {
//!            MyActorScript::Increment {} => {
//!                actor.increment();
//!            }
//!            MyActorScript::AddNumber {
//!                input: (num),
//!                output: send,
//!            } => {
//!                send.send(actor.add_number(num))
//!                    .expect("'my_actor_direct.send'. Channel closed");
//!            }
//!            MyActorScript::GetValue { output: send } => {
//!                send.send(actor.get_value())
//!                    .expect("'my_actor_direct.send'. Channel closed");
//!            }
//!        }
//!    }
//!}
//! 
//! ```
//! 
//! # play
//! The function  `actor_name_ + play` responsible for 
//! continuously receiving `script` variants from 
//! a dedicated channel and `direct`ing them.
//! 
//! Also this function serves as the home for the Actor itself.
//! 
//! 
//!```rust
//!pub fn my_actor_play(
//!    receiver: std::sync::mpsc::Receiver<MyActorScript>, 
//!    mut actor: MyActor) {
//! 
//!    while let Ok(msg) = receiver.recv() {
//!        msg.my_actor_direct(&mut actor);
//!    }
//!    eprintln!("MyActor end of life ...");
//!}
//!``` 
//! 
//! When using the [`edit`](./attr.actor.html#edit) argument in the [`actor`](./attr.actor.html) 
//! macro, such as 
//! 
//!```rust
//!#[interthread::actor(channel=2, edit(play))]
//!``` 
//! 
//! it allows for manual implementation of the `play` part, which 
//! gives the flexibility to customize and modify 
//! the behavior of the `play` to suit any requared logic.
//! 
//! 
//! # live
//! A struct `ActorName + Live`, which serves as an interface/handler 
//! replicating the public method signatures of the original Actor.
//! 
//! Invoking a method on a live instance, it's triggering the eventual 
//! invocation of the corresponding method within the Actor. 
//! 
//! The `live` method `new` is creating : new channel, an instace of 
//! the Actor,
//! spawning the `play` component in a separate 
//! thread allowing for parallel execution,
//! returns an instance of `Self`.
//! 
//! 
//! ```rust 
//! 
//!impl MyActorLive {
//!    pub fn new(v: i8) -> Self {
//!        let (sender, receiver) = std::sync::mpsc::sync_channel(2);
//!        let actor = MyActor::new(v);
//!        let actor_live = Self { sender };
//!        std::thread::spawn(|| my_actor_play(receiver, actor));
//!        actor_live
//!    }
//!    pub fn increment(&mut self) {
//!        let msg = MyActorScript::Increment {};
//!        let _ = self
//!            .sender
//!            .send(msg)
//!            .expect("'MyActorLive::method.send'. Channel is closed!");
//!    }
//!    pub fn add_number(&mut self, num: i8) -> i8 {
//!        let (send, recv) = oneshot::channel();
//!        let msg = MyActorScript::AddNumber {
//!            input: (num),
//!            output: send,
//!        };
//!        let _ = self
//!            .sender
//!            .send(msg)
//!            .expect("'MyActorLive::method.send'. Channel is closed!");
//!        recv.recv()
//!            .expect("'MyActorLive::method.recv'. Channel is closed!")
//!    }
//!    pub fn get_value(&self) -> i8 {
//!        let (send, recv) = oneshot::channel();
//!        let msg = MyActorScript::GetValue { output: send };
//!        let _ = self
//!            .sender
//!            .send(msg)
//!            .expect("'MyActorLive::method.send'. Channel is closed!");
//!        recv.recv()
//!            .expect("'MyActorLive::method.recv'. Channel is closed!")
//!    }
//!}
//! 
//! ```
//! 
//! 
//! # Panics
//! 
//! If the types used for input or output for actor methods 
//! do not implement the `Send`, `Sync`, and `Debug` traits.
//! 
//! Additionally, the actor object itself should implement 
//! the `Send` trait, allowing it to be safely moved 
//! to another thread for execution. 
//! 
//! # Macro Implicit Dependencies
//!
//! The [`actor`](./attr.actor.html) macro generates code
//! that utilizes channels for communication. However, 
//! the macro itself does not provide any channel implementations.
//! Therefore, depending on the libraries used in your project, 
//! you may need to import additional crates.
//!
//!### Crate Compatibility
//!<table>
//!  <thead>
//!    <tr>
//!      <th>lib</th>
//!      <th><a href="https://docs.rs/oneshot">oneshot</a></th>
//!      <th><a href="https://docs.rs/async-channel">async_channel</a></th>
//!    </tr>
//!  </thead>
//!  <tbody>
//!    <tr>
//!      <td>std</td>
//!      <td style="text-align: center;">&#10003;</td>
//!      <td style="text-align: center;"><b>-</b></td>
//!    </tr>
//!    <tr>
//!      <td><a href="https://crates.io/crates/smol">smol</a></td>
//!      <td style="text-align: center;">&#10003;</td>
//!      <td style="text-align: center;">&#10003;</td>
//!    </tr>
//!    <tr>
//!      <td><a href="https://docs.rs/tokio">tokio</a></td>
//!      <td style="text-align: center;"><b>-</b></td>
//!      <td style="text-align: center;"><b>-</b></td>
//!    </tr>
//!    <tr>
//!      <td><a href="https://crates.io/crates/async-std">async-std</a></td>
//!      <td style="text-align: center;">&#10003;</td>
//!      <td style="text-align: center;"><b>-</b></td>
//!    </tr>
//!  </tbody>
//!</table>
//!
//! 
//!>**Note:** The table shows the compatibility of 
//!>the macro with different libraries, indicating whether 
//!>the dependencies are needed (✔) or not. 
//!>The macros will provide helpful messages indicating 
//!>the necessary crate imports based on your project's dependencies.
 

mod attribute;
mod use_macro;
mod show;
mod file;
mod actor_gen;
mod name;
mod method;
mod check;
mod error;


static INTERTHREAD: &'static str            = "interthread";
static INTER_EXAMPLE_DIR_NAME: &'static str = "INTER_EXAMPLE_DIR_NAME";
static INTER: &'static str                  = "inter";
static GROUP: &'static str                  = "group";
static ACTOR: &'static str                  = "actor";
static EXAMPLE: &'static str                = "example";
static EXAMPLES: &'static str               = "examples";


/// # Code transparency and exploration
///  
/// The [`example`](./attr.example.html) macro serves as a 
/// convenient tool for code transparency and exploration.
/// Automatically generating an expanded code file,
/// it provides developers with a tangible representation of
/// the code produced by the `interthread` macros. 
/// 
/// Having the expanded code readily available in the `examples/inter`
/// directory offers a few key advantages:
///  
/// - It provides a clear reference point for developers to inspect 
/// and understand the underlying code structure.
/// 
/// - The generated code file serves as a starting point for 
/// customization. Developers can copy and paste the generated code 
/// into their own project files and make custom changes as needed. 
/// This allows for easy customization of the generated actor 
/// implementation to fit specific requirements or to add additional 
/// functionality.
/// 
/// - Helps maintain a clean and focused project structure, 
/// with the `examples` directory serving as a dedicated location for 
/// exploring and experimenting with the generated code.
/// 
/// [`example`](./attr.example.html) macro helps developers to 
/// actively engage with the generated code 
/// and facilitates a smooth transition from the generated code to a 
/// customized implementation. This approach promotes code transparency,
/// customization, and a better understanding of the generated code's 
/// inner workings, ultimately enhancing the development experience 
/// when working with the `interthread` macros.
/// 
/// Consider a macro [`actor`](./attr.actor.html)  inside the project 
/// in `src/my_file.rs`.
/// 
///Filename: my_file.rs 
///```rust
///use interthread::{actor,example};
///
///pub struct Number;
///
/// // you can have "example" macro in the same file
/// // #[example(file="src/my_file.rs")]
///
///#[actor(channel=5)]
///impl Number {
///    pub fn new(value: u32) -> Self {Self}
///}
///
///```
/// 
///Filename: main.rs 
///```rust
///use interthread::example;
///#[example(file="src/my_file.rs")]
///fn main(){
///}
///
///```
/// 
/// The macro will create and write to `examples/inter/my_file.rs`
/// the content of `src/my_file.rs` with the 
/// [`actor`](./attr.actor.html) macro expanded.
/// 
/// 
///```text
///my_project/
///├── src/
///│  ├── my_file.rs      <---  macro "actor" 
///|  |
///│  └── main.rs         <---  macro "example" 
///|
///├── examples/          
///   ├── ...
///   └── inter/      
///      ├── my_file.rs   <--- expanded "src/my_file.rs"  
///```
///
/// [`example`](./attr.example.html) macro can be placed on any 
/// item in any file within your `src` directory, providing 
/// flexibility in generating example code for/from different 
/// parts of your project.
///
/// It provides two options for generating example code files: 
///  - [`mod`](##mod)  (default)
///  - [`main`](##main) 
///
/// ## mod 
/// The macro generates an example code file within the 
/// `examples/inter` directory. For example:
///
///```rust
///#[example(file="my_file.rs")]
///```
///
/// This is equivalent to:
///
///```rust
///#[example(mod(file="my_file.rs"))]
///```
///
/// The generated example code file will be located at 
/// `examples/inter/my_file.rs`.
///
/// This option provides developers with an easy way to 
/// view and analyze the generated code, facilitating code 
/// inspection and potential code reuse.
///
/// ## main 
///
/// This option is used when specifying the `main` argument 
/// in the `example` macro. It generates two files within 
/// the `examples/inter` directory: the expanded code file 
/// and an additional `main.rs` file. 
///
///```rust
///#[example(main(file="my_file.rs"))]
///```
///
/// This option is particularly useful for testing and 
/// experimentation. It allows developers to quickly 
/// run and interact with the generated code by executing:
///
///```terminal
///$ cargo run --example inter
///```
///
/// The expanded code file will be located at 
/// `examples/inter/my_file.rs`, while the `main.rs` file 
/// serves as an entry point for running the example.
/// 
/// ## Configuration Options  
///```text 
/// 
///#[interthread::example( 
///   
///    mod ✔
///    main 
///
///    (   
///        file = "path/to/file.rs" ❗️ 
///
///        expand(actor,group) ✔
///    )
/// )]
/// 
/// 
/// default:    ✔
/// required:   ❗️
/// 
/// 
///```
/// 
/// # Arguments
/// 
/// - [`file`](#file)
/// - [`expand`](#expand) (default)
/// 
/// # file
/// 
/// 
/// The file argument is a required parameter of the example macro.
/// It expects the path to the file that needs to be expanded.
/// 
/// This argument is essential as it specifies the target file 
/// for code expansion.
/// One more time [`example`](./attr.example.html) macro can be 
/// placed on any item in any file within your `src` directory.
/// 
///  
/// # expand
/// 
/// This argument allows the user to specify which 
/// `interthread` macros to expand. 
/// 
/// By default, the value of `expand` includes 
/// the [`actor`](./attr.actor.html) and 
/// [`group`](./attr.group.html) macros.
/// 
/// For example, if you want to expand only the
/// [`actor`](./attr.actor.html) macro in the generated 
/// example code, you can use the following attribute:
/// 
/// ```rust
/// #[example(file="my_file.rs",expand(actor))]
/// ```
/// This will generate an example code file that includes 
/// the expanded code of the [`actor`](./attr.actor.html) macro,
/// while excluding other macros like 
/// [`group`](./attr.group.html).
/// 
 

#[proc_macro_error::proc_macro_error]
#[proc_macro_attribute]
pub fn example( attr: proc_macro::TokenStream, _item: proc_macro::TokenStream ) -> proc_macro::TokenStream {

    let mut eaa   = attribute::ExampleAttributeArguments::default();

    let aaa_parser = 
    syn::meta::parser(|meta| eaa.parse(meta));
    syn::parse_macro_input!(attr with aaa_parser);


    let (file, lib)  = file::expand_macros(&eaa.get_file(),&eaa.expand);

    let path = if eaa.main { 
        show::example_show(file, &eaa.get_file(), Some(lib))
    } else {
        show::example_show(file, &eaa.get_file(), None ) 
    };

    let msg = format!("The file has been SUCCESSFULLY created at {}",path.to_string_lossy());
    let note  = "To avoid potential issues and improve maintainability, it is recommended to comment out the macro after its successful execution. To proceed, please comment out the macro and re-run the compilation.";
    
    proc_macro_error::abort!( proc_macro2::Span::call_site(),msg; note = note);
    
}

 
/// ## Evolves a regular object into an actor
/// 
/// The macro is placed upon an implement block of an object
///  (`struct` or `enum`),
/// which has a public method named `new` returning  `Self`.
///
/// In case if the initialization could potentially fail, 
/// the method can be named `try_new` 
/// and return `Option<Self>` or `Result<Self>`.
/// 
/// The macro will copy method signatures from all 
/// public methods that do not consume the receiver, excluding 
/// methods like `pub fn bla(self, val: u8) -> ()` where `self` 
/// is consumed. Please ensure that the 
/// receiver is defined as `&self` or `&mut self`. 
/// 
/// It will 
/// also include all associated functions that return a type. 
/// To change this behavior and exclude all associated functions, 
/// regardless of their return type, you can set the [`assoc`](#assoc) 
/// argument of the macro to `false`.
/// 
/// If only a subset of methods is required to be 
/// accessible across threads, split the `impl` block 
/// into two parts. By applying the macro to a specific block, 
/// the macro will only consider the methods within that block.
/// 
/// ## Configuration Options
///```text 
/// 
/// #[interthread::actor( 
///   
///     channel = "inter"    ✔
///          0 || "unbounded" 
///               8 
/// 
///     lib     = "std"      ✔
///               "smol"
///               "tokio"
///               "async_std"
///     
///     edit    (            ✘
///               script
///               direct
///               play
///               live
///               live::new 
///              )           
///      
///     name    = ""         ✘
/// 
///     assoc   = true       ✔
///  
/// )]
/// 
/// default:    ✔
/// no default: ✘
///
///```
///  
/// # Arguments
///  
///
/// - [`channel`](#channel)
/// - [`lib`](#lib) 
/// - [`edit`](#edit)
/// - [`name`](#name)
/// - [`assoc`](#assoc)
///
/// 
/// 
/// # channel
///
/// The `channel` argument specifies the type of channel. 
///
/// - `"inter"` (default)  
/// - `"unbounded"` or `0` 
/// - `8` ( [`usize`] buffer size)
/// > **Note:** The default `"inter"` option is experimental 
/// and primarily intended for experimentation purposes, 
/// specifically with the `lib = "std"` setting. 
/// It is recommended to avoid using this option 
/// unless you need it.
/// 
/// The two macros
/// ```rust
/// #[actor(channel="unbounded")]
/// ```
/// and
/// ```rust
/// #[actor(channel=0)]
/// ```
/// are identical and both specify an unbounded channel.
/// 
/// When specifying an [`usize`] value for the `channel` argument 
/// in the [`actor`](./attr.actor.html) macro, such as 
/// ```rust
/// #[actor(channel=4)]
/// ```
/// the actor will use a bounded channel with a buffer size of 4.
/// This means that the channel can hold up to 4 messages in its 
/// buffer before blocking/suspending the sender.
///
/// Using a bounded channel with a specific buffer size allows 
/// you to control the memory usage and backpressure behavior 
/// of the actor. When the buffer is full, any further attempts 
/// to send messages will block/suspend until there is available space. 
/// This provides a natural form of backpressure, allowing the 
/// sender to slow down or pause message production when the 
/// buffer is near capacity.
/// 
/// # lib
///
/// The `lib` argument specifies the 'async' library to use.
///
/// - `"std"` (default)
/// - `"smol"`
/// - `"tokio"`
/// - `"async_std"`
///
///## Examples
///```rust
///use interthread::actor;
///
///struct MyActor;
///
///#[actor(channel=10, lib ="tokio")]
///impl MyActor{
///    pub fn new() -> Self{Self}
///}
///#[tokio::main]
///async fn main(){
///    let my_act = MyActorLive::new();
///}
///```
/// 
/// 
/// 
/// # edit
///
/// The `edit` argument specifies the available editing options.
/// When using this argument, the macro expansion will 
/// **exclude** the code related to `edit` options, 
/// allowing the user to manually implement and 
/// customize those parts according to their specific needs.
/// 
/// - [`script`](index.html#script)
/// - [`direct`](index.html#direct)
/// - [`play`](index.html#play)
/// - [`live`](index.html#live)
/// - `live::new`  
///
/// 
/// ## Examples
///```rust
///
///use std::sync::mpsc;
///use interthread::actor;
/// 
///pub struct MyActor {
///    value: i8,
///}
/// // we will edit `play` function
/// #[actor(channel=2, edit(play))]
///impl MyActor {
///
///    pub fn new( value: i8 ) -> Self {
///        Self{value}
///    }
///    pub fn increment(&mut self) -> i8{
///        self.value += 1;
///        self.value
///    }
///}
///
///// manually create "play" function 
///// use `example` macro to copy paste
///// `play`'s body 
///pub fn my_actor_play( 
///     receiver: mpsc::Receiver<MyActorScript>,
///    mut actor: MyActor) {
///    // set a custom variable 
///    let mut call_counter = 0;
///    while let Ok(msg) = receiver.recv() {
///        // do something 
///        // like 
///        println!("Value of call_counter = {}",call_counter);
///
///        // `direct` as usual 
///        msg.my_actor_direct(&mut actor);
///
///        // increment the counter as well
///        call_counter += 1;
///    }
///    eprintln!(" the end ");
///}
///
///
///fn main() {
///
///    let my_act       = MyActorLive::new(0);
///    let mut act_a = my_act.clone();
///    
///
///    let handle_a = std::thread::spawn(move || -> i8{
///        act_a.increment()
///    });
///
///    let value = handle_a.join().unwrap();
///    
///    assert_eq!(value, 1);
///
///    // and it will print the value of 
///    // call_counter
///}
///```
///
/// > **Note:** The expanded `actor` can be viewed using [`example`](./attr.example.html) macro. 
/// 
/// 
/// Now, let's explore a scenario where we want to manipulate or 
/// even return a type from the [`play`](index.html#play) 
/// component by invoking a method on the [`live`](index.html#live) 
/// component. We can easily modify the generated code to 
/// enable this functionality.
/// 
/// ## Examples
///```rust
///use std::sync::mpsc;
///use interthread::actor;
/// 
///pub struct MyActor {
///    value: i8,
///}
/// #[actor(channel=2, edit(play))]
///impl MyActor {
///
///    pub fn new( value: i8 ) -> Self {
///        Self{value}
///    }
///    pub fn increment(&mut self) -> i8{
///        self.value += 1;
///        self.value
///    }
///    // it's safe to hack the macro in this way
///    // having `&self` as receiver along  with
///    // other things creates a `Script` variant  
///    // We'll catch it in `play` function
///    pub fn play_get_counter(&self)-> Option<u32>{
///        None
///    }
///
///}
///
///// manually create "play" function 
///// use `example` macro to copy paste
///// `play`'s body
///pub fn my_actor_play( 
///     receiver: mpsc::Receiver<MyActorScript>,
///    mut actor: MyActor) {
///    // set a custom variable 
///    let mut call_counter = 0;
///
///    while let Ok(msg) = receiver.recv() {
///
///        // match incoming msgs
///        // for `play_get_counter` variant
///        match msg {
///            // you don't have to remember the 
///            // the name of the `Script` variant 
///            // your text editor does it for you
///            // so just choose the variant
///            MyActorScript::PlayGetCounter { output  } =>
///            { let _ = output.send(Some(call_counter));},
///            
///            // else as usual 
///            _ => { msg.my_actor_direct(&mut actor); }
///        }
///        call_counter += 1;
///    }
///    eprintln!("the end");
///}
///
///
///fn main() {
///
///    let my_act = MyActorLive::new(0);
///    let mut act_a = my_act.clone();
///    let mut act_b = my_act.clone();
///
///    let handle_a = std::thread::spawn(move || {
///        act_a.increment();
///    });
///    let handle_b = std::thread::spawn(move || {
///        act_b.increment();
///    });
///    
///    let _ = handle_a.join();
///    let _ = handle_b.join();
///
///
///    let handle_c = std::thread::spawn(move || {
///
///        // as usual we invoke a method on `live` instance
///        // which has the same name as on the Actor object
///        // but 
///        if let Some(counter) = my_act.play_get_counter(){
///
///            println!("This call never riched the `Actor`, 
///            it returns the value of total calls from the 
///            `play` function ,call_counter = {:?}",counter);
///
///            assert_eq!(counter, 2);
///        }
///    });
///    let _ = handle_c.join();
///
///}
///```
/// Let's take a moment to rearrange our example. 
/// 
/// 
/// ## Examples
///```rust
///use std::sync::mpsc;
///use interthread::actor;
/// 
///pub struct MyActor {
///    value: i8,
///}
/// #[actor(channel=2, edit(play))]
///impl MyActor {
///
///    pub fn new( value: i8 ) -> Self {
///        Self{value}
///    }
///    pub fn increment(&mut self) -> i8{
///        self.value += 1;
///        self.value
///    }
///    pub fn play_get_counter(&self)-> Option<u32>{
///        None
///    }
///
///}
///
///
///// incapsulate the matching block
///// inside `Script` impl block
///// where the `direct`ing is happening
///// to keep our `play` function nice
///// and tidy 
///impl MyActorScript {
///    pub fn custom_direct(self,
///           actor: &mut MyActor, 
///           counter: &u32 ){
///
///        // the same mathing block 
///        // as in above example    
///        match self {
///            MyActorScript::PlayGetCounter { output  } =>
///            { let _ = output.send(Some(counter.clone()));},
///            
///            // else as usual 
///            msg => { msg.my_actor_direct(actor); }
///        }
///    } 
///}
///
///// manually create "play" function 
///// use `example` macro to copy paste
///// `play`'s body
///pub fn my_actor_play( 
///     receiver: mpsc::Receiver<MyActorScript>,
///    mut actor: MyActor) {
///    // set a custom variable 
///    let mut call_counter = 0;
///    
///    // nice and tidy while loop ready
///    // for more wild things to happen
///    while let Ok(msg) = receiver.recv() {
///        
///        // this is the invocation
///        // of MyActorScript.custom_direct()
///        msg.custom_direct(&mut actor, &call_counter);
///
///        call_counter += 1;
///    }
///    eprintln!("the end");
///}
///
///
///fn main() {
///
///    let my_act = MyActorLive::new(0);
///    let mut act_a = my_act.clone();
///    let mut act_b = my_act.clone();
///
///    let handle_a = std::thread::spawn(move || {
///        act_a.increment();
///    });
///    let handle_b = std::thread::spawn(move || {
///        act_b.increment();
///    });
///    
///    let _ = handle_a.join();
///    let _ = handle_b.join();
///
///
///    let handle_c = std::thread::spawn(move || {
///
///        if let Some(counter) = my_act.play_get_counter(){
///
///            println!("This call never riched the `Actor`, 
///            it returns the value of total calls from the 
///            `play` function ,call_counter = {:?}",counter);
///
///            assert_eq!(counter, 2);
///        }
///    });
///    let _ = handle_c.join();
///
///}
///```
/// 
/// # name
/// 
/// The `name` attribute allows developers to provide a 
/// custom name for `actor`, overriding the default 
/// naming conventions of the crate. This can be useful 
/// when there are naming conflicts or when a specific 
/// naming scheme is desired.  
/// 
/// - "" (default): No name specified
///
/// ## Examples
///```rust
///use interthread::actor;
/// 
///pub struct MyActor;
/// 
///#[actor(name="OtherActor")]
///impl MyActor {
///
///   pub fn new() -> Self {Self}
///}
///fn main () {
///   let other_act = OtherActorLive::new();
///}
///```
/// 
/// 
/// 
/// # assoc
/// 
/// The `assoc` option indicates whether **associated**  **functions**
/// of the actor struct are included in generated code as 
/// instance methods, allowing them to be invoked on 
/// the generated struct itself. 
/// 
/// - true  (default)
/// - false
/// 
///  ## Examples
///```rust
///use interthread::actor;
///pub struct Aa;
///  
/// 
///#[actor(name="Bb")]
///impl Aa {
///
///    pub fn new() -> Self { Self{} }
///
///    pub fn is_even( n: u8 ) -> bool {
///        n % 2 == 0
///    }
///}
///
///fn main() {
///    
///    let bb = BbLive::new();
///    assert_eq!(bb.is_even(84), Aa::is_even(84));
///}
/// ```
/// An [`actor`](./attr.actor.html) macro as
/// ```rust
/// #[actor(name="Bb",assoc=false)]
/// ```
/// on the same object `Aa` will create a type `BbLive`
/// without any methods defined.
///


#[proc_macro_error::proc_macro_error]
#[proc_macro_attribute]
pub fn actor( attr: proc_macro::TokenStream, item: proc_macro::TokenStream ) -> proc_macro::TokenStream {
    
    let impl_block                      = syn::parse_macro_input!(item as syn::ItemImpl);
    let mut paaa    = attribute::ParseActorAttributeArguments::default();

    let attr_str = attr.clone().to_string();

    if !attr_str.is_empty(){

        let aaa_parser  = 
        syn::meta::parser(|meta| paaa.parse(meta));
        syn::parse_macro_input!(attr with aaa_parser);
    }
    let aaa = paaa.get_arguments();

    check::channels_import( &aaa.lib );
    
    let mut inter_gen_actor = actor_gen::ActorMacroGeneration::new( /*name,*/ aaa, impl_block );
    let code = inter_gen_actor.generate();
    quote::quote!{#code}.into()
   
}

/// ## Currently under development (((
/// 
/// The `group` macro, although not currently included 
/// in the `interthread` crate.It aims to address 
/// several critical challenges encountered when
///  working with the `actor` macro:
/// 
/// - Instead of creating separate threads for each object, 
/// the `group` macro will enable the user to create an actor 
/// that represents a group of objects, consolidating 
/// their processing and execution within a single thread.
/// 
/// 
/// - In scenarios where objects are already created or imported,
/// and the user does not have the authority to implement 
/// additional methods such as  "new" or "try_new",
/// the `group` macro should offer a way to include 
/// these objects as part of the actor system.
///
/// Although the `group` macro is not currently part of the 
/// `interthread` crate, its development aims to offer a 
/// comprehensive solution to these challenges, empowering 
/// users to efficiently manage groups of objects within an 
/// actor system.
/// 
/// Check `interthread` on ['GitHub'](https://github.com/NimonSour/interthread.git)
/// 

#[proc_macro_error::proc_macro_error]
#[proc_macro_attribute]
pub fn group( _attr: proc_macro::TokenStream, _item: proc_macro::TokenStream ) -> proc_macro::TokenStream {
    let msg = "The \"group\" macro is currently under development and is not yet implemented in the `interthread` crate.";
    proc_macro_error::abort!( proc_macro2::Span::call_site(),msg );
}