starlane-primitive-macros 0.3.21

Some primitive macros needed to jump start starlane
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
/*#![feature(proc_macro_quote)]*/
#![crate_type = "lib"]
#![allow(warnings)]
#[feature("proc_macro_lib2")]
#[macro_use]
extern crate quote;

use proc_macro::TokenStream;
use proc_macro2::Ident;
use proc_macro_crate::{crate_name, FoundCrate};
use quote::quote;
use quote::ToTokens;
use syn::__private::TokenStream2;
use syn::token::Mut;
use syn::{
    parse_file, parse_macro_input, AttrStyle, Attribute, AttributeArgs, Data, DeriveInput, Expr,
    ExprTuple, File, FnArg, ImplItem, ItemImpl, LitStr, PatType, PathArguments, Token, Type,
    Visibility,
};

/// Takes a given enum (which in turn accepts child enums) and auto generates a `Parent::From` so the child
/// can turn into the parent and a `TryInto<Child> for Parent` so the Parent can attempt to turn into the child.
/// ```
/// #[derive(Autobox)]
/// pub enum Parent {
///   Child(Child)
/// }
///
/// pub enum Child {
///   Variant1,
///   Variant2
/// }
/// ```
/// Will generate something like:
/// ```
/// //impl Autobox for Parent { }
///
/// impl From<Child> for Parent {
///   fn from( child: Child ) -> Self {
///      Self::Child(child)
///   }
/// }
///
/// impl TryInto<Child> for Parent {
///   type Err=ParseErrs;
///
///   fn try_into(self) -> Result<Child,Self::Err> {
///     if let Self::Child(child) = self {
///        Ok(self)
///     } else {
///        Err("err")
///     }
///   }
/// }
/// ```
#[proc_macro_derive(Autobox)]
pub fn autobox(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let ident = &input.ident;

    let mut xforms = vec![];
    if let Data::Enum(data) = &input.data {
        for variant in data.variants.clone() {
            if variant.fields.len() > 1 {
                panic!("derive Transform only works on Enums with single value tuples")
            }

            let variant_ident = variant.ident.clone();

            if variant.fields.len() == 1 {
                let mut i = variant.fields.iter();
                let field = i.next().unwrap().clone();
                let ty = field.ty.clone();
                match ty {
                    Type::Path(path) => {
                        let segment = path.path.segments.last().cloned().unwrap();
                        if segment.ident == format_ident!("{}", "Box") {
                            let ty = match segment.arguments {
                                PathArguments::AngleBracketed(ty) => {
                                    format_ident!("{}", ty.args.to_token_stream().to_string())
                                }
                                _ => panic!("expecting angle brackets"),
                            };

                            let ty_str = ty.to_string();

                            xforms.push(quote! {
                                impl TryInto<#ty> for #ident {
                                    type Error=ParseErrs;

                                    fn try_into(self) -> Result<#ty,Self::Error> {
                                        match self {
                                        Self::#variant_ident(val) => Ok(*val),
                                        _ => Err(ParseErrs::new(format!("expected {}",#ty_str)))
                                        }
                                    }
                                }


                                impl From<#ty> for #ident {
                                    fn from(f: #ty) -> #ident {
                                    #ident::#variant_ident(Box::new(f))
                                }
                            }
                                    });
                        } else {
                            let ty = segment.ident;
                            let ty_str = ty.to_token_stream().to_string();
                            xforms.push(quote! {
                                impl TryInto<#ty> for #ident {
                                    type Error=ParseErrs;

                                    fn try_into(self) -> Result<#ty,Self::Error> {
                                        match self {
                                            Self::#variant_ident(val) => Ok(val),
                                            _ => Err(ParseErrs::new(format!("expected {}",#ty_str)))
                                        }
                                    }
                                }


                                impl From<#ty> for #ident {
                                    fn from(f: #ty) -> #ident {
                                        #ident::#variant_ident(f)
                                    }
                                }
                            });
                        }
                    }
                    _ => {
                        panic!("TransformVariants can only handle Path types")
                    }
                }
            }
        }
    } else {
        panic!("derive Transform only works on Enums")
    }

    let rtn = quote! { #(#xforms)* };

    rtn.into()
}

#[proc_macro_derive(ToSubstance)]
pub fn to_substance(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let ident = &input.ident;

    let mut xforms = vec![];
    if let Data::Enum(data) = &input.data {
        for variant in data.variants.clone() {
            if variant.fields.len() > 1 {
                panic!("derive Transform only works on Enums with single value tuples")
            }

            let variant_ident = variant.ident.clone();

            if variant.fields.len() == 1 {
                let mut i = variant.fields.iter();
                let field = i.next().unwrap().clone();
                let ty = field.ty.clone();
                match ty {
                    Type::Path(path) => {
                        let segment = path.path.segments.last().cloned().unwrap();
                        if segment.ident == format_ident!("{}", "Box") {
                            let ty = match segment.arguments {
                                PathArguments::AngleBracketed(ty) => {
                                    format_ident!("{}", ty.args.to_token_stream().to_string())
                                }
                                _ => panic!("expecting angle brackets"),
                            };

                            let ty_str = ty.to_string();

                            xforms.push(quote! {
                            impl ToSubstance<#ty> for #ident {
                                fn to_substance(self) -> Result<#ty,ParseErrs> {
                                    match self {
                                    Self::#variant_ident(val) => Ok(*val),
                                    _ => Err(ParseErrs::new(format!("expected {}",#ty_str)))
                                    }
                                }

                                fn to_substance_ref(&self) -> Result<&#ty,ParseErrs> {
                                    match self {
                                    Self::#variant_ident(val) => Ok(val.as_ref()),
                                    _ => Err(ParseErrs::new(format!("expected {}",#ty_str)))
                                    }
                                }
                            }

                                });
                        } else {
                            let ty = segment.ident;
                            let ty_str = ty.to_token_stream().to_string();
                            xforms.push(quote! {
                            impl ToSubstance<#ty> for #ident {
                                fn to_substance(self) -> Result<#ty,ParseErrs> {
                                    match self {
                                    Self::#variant_ident(val) => Ok(val),
                                    _ => Err(ParseErrs::new(format!("expected {}",#ty_str)))
                                    }
                                }
                                 fn to_substance_ref(&self) -> Result<&#ty,ParseErrs> {
                                    match self {
                                    Self::#variant_ident(val) => Ok(val),
                                    _ => Err(ParseErrs::new(format!("expected {}",#ty_str)))
                                    }
                                }
                            }

                            });
                        }
                    }
                    _ => {
                        panic!("ToSubstance can only handle Path types")
                    }
                }
            } else {
                xforms.push(quote! {
                impl ToSubstance<()> for #ident {
                    fn to_substance(self) -> Result<(),ParseErrs> {
                        match self {
                        Self::#variant_ident => Ok(()),
                        _ => Err(ParseErrs::new(format!("expected Empty")))
                        }
                    }
                     fn to_substance_ref(&self) -> Result<&(),ParseErrs> {
                        match self {
                        Self::#variant_ident => Ok(&()),
                        _ => Err(ParseErrs::new(format!("expected Empty")))
                        }
                    }
                }

                });
            }
        }
    } else {
        panic!("derive ToSubstance only works on Enums")
    }

    let rtn = quote! { #(#xforms)* };

    rtn.into()
}

/*
#[proc_macro_derive(MechErr)]
pub fn mech_err(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let ident = &input.ident;

    let from = vec![
        quote!(Box<bincode::ErrorKind>),
        quote!(mechtron::err::MembraneErr),
        quote!(starlane::err::ParseErrs),
        quote!(String),
        quote!(&'static str),
        quote!(mechtron::err::GuestErr),
        quote!(std::string::FromUtf8Error),
    ];

    let rtn = quote! {

        impl MechErr for #ident {
            fn to_uni_err(self) -> starlane::err::{
               starlane::err::SpaceErr::server_error(self.to_string())
            }
        }

        impl From<#ident> for mechtron::err::GuestErr{
            fn from(e: #ident) -> Self {
                        mechtron::err::GuestErr {
                            message: e.to_string()
                        }
            }
        }

        impl starlane::err::CoreReflector for #ident {
                fn as_reflected_core(self) -> starlane::wave::core::ReflectedCore {
                   starlane::wave::core::ReflectedCore{
                        headers: Default::default(),
                        status: starlane::wave::core::http2::StatusCode::from_u16(500u16).unwrap(),
                        body: self.into().into()
                    }
            }
        }


        impl ToString for #ident {
            fn to_string(&self) -> String {
                self.message.clone()
            }
        }

        #(
            impl From<#from> for #ident {
                fn from(e: #from ) -> Self {
                    Self {
                        message: e.to_string()
                    }
                }
            }
        )*
    };
    //println!("{}", rtn.to_string());
    rtn)
}

 */

#[proc_macro_derive(ToBase)]
pub fn base(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let ident = &input.ident;
    let base = format_ident!("{}Base", ident);
    let mut variants: Vec<Ident> = vec![];

    if let Data::Enum(data) = &input.data {
        for variant in data.variants.clone() {
            variants.push(variant.ident.clone());
        }
    }

    let rtn = quote! {
        pub enum #base {
        #(#variants),*
        }


        #[allow(bindings_with_variant_name)]
        impl ToString for #base {
            fn to_string(&self) -> String {
                match self {
            #( #variants => "#variants".to_string() ),*
                }
            }
        }
    };

    rtn.into()
}

#[proc_macro_derive(ToLogMark)]
pub fn to_log_mark(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let ident = &input.ident;
    let base = format_ident!("{}Base", ident);
    let mut variants: Vec<Ident> = vec![];

    if let Data::Enum(data) = &input.data {
        for variant in data.variants.clone() {
            variants.push(variant.ident.clone());
        }
    }

    let rtn = quote! {
        pub enum #base {
        #(#variants),*
        }


        #[allow(bindings_with_variant_name)]
        impl ToString for #base {
            fn to_string(&self) -> String {
                match self {
            #( #variants => "#variants".to_string() ),*
                }
            }
        }
    };

    rtn.into()
}

#[cfg(test)]
mod tests {
    #[test]
    fn it_works() {
        let result = 2 + 2;
        assert_eq!(result, 4);
    }
}

#[proc_macro_derive(EnumAsStr)]
pub fn directed_handler(item: TokenStream) -> TokenStream {
    TokenStream::from(quote! {})
}

#[proc_macro_attribute]
pub fn loggerhead(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut out = vec![];
    let input = parse_macro_input!(item as File);
    for item in input.items.into_iter() {
        let item = quote!(#item);
        println!("running parser over {}", item);
        out.push(item);
    }

    let rtn = quote! {
        #(#out)*
    };

    rtn.into()
}

#[proc_macro]
pub fn push_loc(tokens: TokenStream) -> TokenStream {
    let crt = crt_name();
    let tuple = parse_macro_input!(tokens as ExprTuple);
    let mut iter = tuple.elems.into_iter();
    let logger = iter.next().unwrap();
    let loc = iter.next().unwrap();

    let rtn = quote! {
        {
    let mut builder = #crt::space::log::LogMarkBuilder::default();
    builder.package(env!("CARGO_PKG_NAME").to_string());
    builder.file(file!().to_string());
    builder.line(line!().to_string());
    let mark = builder.build().unwrap();
    #logger.push(#loc)
            }
        };

    rtn.into()
}

#[proc_macro]
pub fn log_span(tokens: TokenStream) -> TokenStream {
    let crt = crt_name();
    let input = parse_macro_input!(tokens as Expr);
    let rtn = quote! {
        {
    let mut builder = #crt::space::log::LogMarkBuilder::default();
    builder.package(env!("CARGO_PKG_NAME").to_string());
    builder.file(file!().to_string());
    builder.line(line!().to_string());
    let mark = builder.build().unwrap();
    #input.push_mark(mark)
            }
        };

    rtn.into()
}

#[proc_macro]
pub fn logger(item: TokenStream) -> TokenStream {
    let crt = crt_name();
    let log_pack = quote!(#crt::space::log);

    let loc = if !item.is_empty() {
        let expr = parse_macro_input!(item as Expr);
        quote!( #log_pack::logger().push(#expr); )
    } else {
        quote!( #log_pack::logger(); )
    };

    let rtn = quote! {
        {
            let logger = #loc;
    let mut builder = #log_pack::LogMarkBuilder::default();
    builder.package(env!("CARGO_PKG_NAME").to_string());
    builder.file(file!().to_string());
    builder.line(line!().to_string());
    let mark = builder.build().unwrap();
            logger.push_mark(mark)
            }
        };

    rtn.into()
}

#[proc_macro]
pub fn push_mark(_item: TokenStream) -> TokenStream {
    let crt = crt_name();
    let logger = parse_macro_input!(_item as Expr);
    let rtn = quote! {
        {
    let mut builder = #crt::space::log::LogMarkBuilder::default();
    builder.package(env!("CARGO_PKG_NAME").to_string());
    builder.file(file!().to_string());
    builder.line(line!().to_string());
    let mark  = builder.build().unwrap();
    #logger.push_mark(mark)
            }

        };

    rtn.into()

}

#[proc_macro]
pub fn create_mark(_item: TokenStream) -> TokenStream {
    let crt = crt_name();
    let rtn = quote! {
        {
println!("CARGO_PKG_NAME: {}", env!("CARGO_PKG_NAME"));
    let mut builder = #crt::space::log::LogMarkBuilder::default();
    builder.package(env!("CARGO_PKG_NAME").to_string());
    builder.file(file!().to_string());
    builder.line(line!().to_string());
    builder.build().unwrap()
            }
        };

    rtn.into()
}

#[proc_macro]
pub fn warn(_item: TokenStream) -> TokenStream {
    let crt = crt_name();
    let input = parse_macro_input!(_item as LitStr);
    let rtn = quote! {

    // pushing scope so we don't collide with
    // any other imports or local things...
    {
        use starlane_primitive_macros::mark;
        use starlane_primitive_macros::create_mark;
        use #crt::space::log::Log;
        use #crt::space::log::LOGGER;
        use #crt::space::log::root_logger;

        // need to push_mark somewhere around here...
        LOGGER.try_with(|logger| {
             logger.warn(stringify!(#input));
        } ).map_err(|e| {
        root_logger().warn(stringify!(#input));
    })
        }
     };
    rtn.into()
}

/*
#[proc_macro_attribute]
pub fn point_log(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut out = vec![];
    let input = parse_macro_input!(item as File);
    for item in input.items.into_iter() {
        let item = quote!(#item);
        println!("running parser over {}", item);
        out.push(item);
    }

    let rtn = quote! {
        #(#out)*
    };

    panic!("~~~ POINT LOG MACRO: {}",rtn.to_string());

    rtn.into()
}

 */

#[proc_macro_attribute]
pub fn log(attr: TokenStream, item: TokenStream) -> TokenStream {
    item.into()
}

#[proc_macro_attribute]
pub fn logger_att(attr: TokenStream, item: TokenStream) -> TokenStream {
    let surface = if attr.is_empty() {
        format_ident!("logger")
    } else {
        format_ident!("{}", attr.to_string())
    };

    let item_cp = item.clone();
    let mut impl_item = parse_macro_input!(item_cp as syn::ItemImpl);
    //    let mut wrappers = vec![];
    //    let mut methods = vec![];

    for item_impl in &impl_item.items {
        if let ImplItem::Method(call) = item_impl {
            {
                let (__async, __await) = match call.sig.asyncness {
                    None => (quote! {}, quote! {}),
                    Some(_) => (quote! {async}, quote! {.await}),
                };

                let mut inner_call = call.clone();
                inner_call.vis = Visibility::Inherited;
                inner_call.sig.ident = format_ident!("__{}", call.sig.ident);
                inner_call.attrs = vec![];
                /*
                let args: Vec<TokenStream>  = inner_call.sig.inputs.clone().into_iter().map( |arg| match arg.clone() {

                   FnArg::Receiver(r) => {
                      let arg = quote!{#r};
                       arg.to_token_stream()

                   },
                    arg => arg.to_token_stream()
                }

                ).collect_into();


                let args = quote!{#( #args )*};
                panic!("ARGS: {}",args.to_string());
                 */
                todo!();

                let attributes = call.attrs.clone();
                let vis = call.vis.clone();
                let sig = call.sig.clone();
                let block = call.block.clone();

                call.clone();
                let blah = quote! {
                   #(#attributes)*
                   #vis
                   #__async
                   #sig
                    {
                        #inner_call
                    }
                };
                panic!("{}", blah);
            }
        }
    }

    //    TokenStream2::from_iter(vec![rtn, TokenStream2::from(item)]).into()
    todo!()
}

fn find_impl_type(item_impl: &ItemImpl) -> Ident {
    if let Type::Path(path) = &*item_impl.self_ty {
        path.path.segments.last().as_ref().unwrap().ident.clone()
    } else {
        panic!("could not get impl name")
    }
}

fn find_log_attr(attrs: &Vec<Attribute>) -> TokenStream {
    for attr in attrs {
        if attr
            .path
            .segments
            .last()
            .expect("segment")
            .to_token_stream()
            .to_string()
            .as_str()
            == "logger"
        {
            let rtn = quote!(#attr);
            return rtn.into();
        }
    }
    let rtn = quote!(logger);
    rtn.into()
}




fn crt_name () -> TokenStream2{
    let found_crate = crate_name("starlane").expect("my-crate is present in `Cargo.toml`");

    let crt = match found_crate {
        FoundCrate::Itself => quote!( crate ),
        FoundCrate::Name(name) => {
            quote!( starlane )
        }
    };
    crt
}