starlane-macros 0.3.17

macros for starlane.io
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
#![crate_type = "lib"]
#![allow(warnings)]

pub(crate) use starlane_space as starlane;

use proc_macro::TokenStream;
use std::str::FromStr;

use chrono::Utc;
use proc_macro2::Ident;
use quote::__private::ext::RepToTokensExt;
use quote::{format_ident, quote, ToTokens};
use starlane::space::loc;
use syn::__private::TokenStream2;
use syn::parse::{Parse, ParseStream};
use syn::parse_quote::ParseQuote;
use syn::spanned::Spanned;
use syn::{parse_macro_input, Attribute, DeriveInput, FnArg, GenericArgument, ImplItem, ItemImpl, PathArguments, PathSegment, ReturnType, Type};

use starlane::space::parse::route_attribute_value;
use starlane::space::util::log;
use starlane::space::wasm::Timestamp;

#[no_mangle]
extern "C" fn cosmic_uuid() -> loc::Uuid {
    loc::Uuid::from(uuid::Uuid::new_v4().to_string()).unwrap()
}

#[no_mangle]
extern "C" fn cosmic_timestamp() -> Timestamp {
    Timestamp::new(Utc::now().timestamp_millis())
}

/// This macro will auto implement the `starlane::space::wave::exchange::asynch::DirectedHandler` trait.
/// In order to finalize the implementation a `#[handler]` attribute must also be specified
/// above one of the impls.
#[proc_macro_derive(DirectedHandler)]
pub fn directed_handler(item: TokenStream) -> TokenStream {
    TokenStream::from(quote! {})
}

/// This impl attribute creates a `fn handler` which receives directed waves and routes them to the first local method
/// which the route selector matches.
/// To implement:
/// ```
///
/// use starlane::space::err::SpaceErr;
/// use starlane::space::hyper::HyperSubstance;
/// use starlane::space::log::PointLogger;
/// use starlane::space::substance::Substance;
/// use starlane::space::substance::Substance::Text;
/// use starlane::space::wave::core::ReflectedCore;
/// use starlane::space::wave::exchange::asynch::InCtx;
///
/// #[derive(DirectedHandler)]
/// pub struct MyHandler {
///   logger: PointLogger
/// }
///
/// #[handler]
// /// impl MyHandler {
// ///     /// the route attribute captures an ExtMethod implementing a custom `MyNameIs`
// ///     /// notice that the InCtx will accept any valid starlane::space::substance::Substance
// ///     #[route("Ext<MyNameIs>")]
// ///     pub async fn hello(&self, ctx: InCtx<'_, Text>) -> Result<String, SpaceErr> {
// ///         /// also we can return any Substance in our Reflected wave
// ///         Ok(format!("Hello, {}", ctx.input.to_string()))
// ///     }
// ///
// ///     /// if the function returns nothing then an Empty Ok Reflected will be returned unless
// ///     /// the wave type is `Wave<Signal>`
// ///     #[route("Ext<Bye>")]
// ///     pub async fn bye(&self, ctx: InCtx<'_,()>) {
// ///        self.logger.info("funny that! He left without saying a word!");
///     }
/// }
#[proc_macro_attribute]
pub fn handler(attr: TokenStream, item: TokenStream) -> TokenStream {
    _handler(attr, item, true)
}

#[proc_macro_attribute]
pub fn handler_sync(attr: TokenStream, item: TokenStream) -> TokenStream {
    _handler(attr, item, false)
}

fn _handler(attr: TokenStream, item: TokenStream, _async: bool) -> TokenStream {
    let item_cp = item.clone();
    let mut impl_item = parse_macro_input!(item_cp as syn::ItemImpl);
    //    let mut selectors = vec![];
    let mut static_selectors = vec![];
    let mut static_selector_keys = vec![];
    let mut idents = vec![];
    let impl_name = find_impl_type(&impl_item);

    //    let mut output = vec![];

    for item_impl in &impl_item.items {
        if let ImplItem::Method(call) = item_impl {
            if let Some(attr) = find_route_attr(&call.attrs) {
                let internal = attr.tokens.to_token_stream().to_string();
                idents.push(format_ident!("__{}__route", call.sig.ident.clone()));
                let selector_ident = format_ident!("__{}_{}__", impl_name, call.sig.ident);
                let route_selector = attr.to_token_stream().to_string();
                static_selector_keys.push(selector_ident.clone());
                let static_selector = quote! {
                    static ref #selector_ident : starlane::space::config::bind::RouteSelector = starlane::space::parse::route_attribute(#route_selector).unwrap();
                };
                static_selectors.push(static_selector);
            //println!(" ~~ ROUTE {}", attr.tokens.to_string() );
            /*                let route = route( attr.to_token_stream().into(), call.to_token_stream().into() );
                           let mut route = parse_macro_input!(route as syn::ImplItem );
                           output.push(route);

            */
            } else {
                //                output.push( ImplItem::Method(call) );
            }
        } else {
            //           output.push( item_impl );
        }
    }

    //    impl_item.items.append( & mut output );

    let self_ty = impl_item.self_ty.clone();
    let generics = impl_item.generics.clone();
    let where_clause = impl_item.generics.where_clause.clone();

    let attr: TokenStream2 = attr.into();

    let rtn = if attr.is_empty() {
        quote! {Ok(RespCore::not_found())}
    } else {
        let rtn = match _async {
            true => quote! {
            #attr.handle(request).await },
            false => quote! {
            #attr.handler.handle(request) },
        };
        rtn
    };

    let selector = match _async {
        true => quote! {starlane::space::wave::exchange::asynch::DirectedHandlerSelector},
        false => quote! {starlane::space::wave::exchange::synch::DirectedHandlerSelector},
    };

    let handler = match _async {
        true => quote! {starlane::space::wave::exchange::asynch::DirectedHandler},
        false => quote! {starlane::space::wave::exchange::synch::DirectedHandler},
    };

    let root_ctx = match _async {
        true => quote! {starlane::space::wave::exchange::asynch::RootInCtx},
        false => quote! {starlane::space::wave::exchange::synch::RootInCtx},
    };

    let _await = match _async {
        true => quote! {.await},
        false => quote! {},
    };

    let _async_trait = match _async {
        true => quote! {#[async_trait]},
        false => quote! {},
    };

    let _async = match _async {
        true => quote! {async},
        false => quote! {},
    };

    let rtn = quote! {
        impl #generics #selector for #self_ty #where_clause{
              fn select<'a>( &self, select: &'a starlane::space::wave::RecipientSelector<'a>, ) -> Result<&dyn #handler, ()> {
                if select.wave.core().method == starlane::space::wave::core::Method::Cmd(starlane::space::wave::core::cmd::CmdMethod::Bounce) {
                    return Ok(self);
                }
                #(
                    if #static_selector_keys.is_match(&select.wave).is_ok() {
                        return Ok(self);
                    }
                )*
                Err(())
              }
        }

        #_async_trait
        impl #generics #handler for #self_ty #where_clause{
            #_async fn handle( &self, ctx: #root_ctx) -> starlane::space::wave::core::CoreBounce {
                #(
                    if #static_selector_keys.is_match(&ctx.wave).is_ok() {
                       return self.#idents( ctx )#_await;
                    }
                )*
                if ctx.wave.core().method == starlane::space::wave::core::Method::Cmd(starlane::space::wave::core::cmd::CmdMethod::Bounce) {
                    return self.bounce(ctx)#_await;
                }
                ctx.not_found().into()
             }
        }

        lazy_static! {
            #( #static_selectors )*
        }

    };

    //    println!("{}", rtn.to_string());

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

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_route_attr(attrs: &Vec<Attribute>) -> Option<Attribute> {
    for attr in attrs {
        if attr
            .path
            .segments
            .last()
            .expect("segment")
            .to_token_stream()
            .to_string()
            .as_str()
            == "route"
        {
            return Some(attr.clone());
        }
    }
    return None;
}

/*
#[proc_macro_attribute]
pub fn route(attr: TokenStream, item: TokenStream ) -> TokenStream {
    item
}

 */

#[proc_macro_attribute]
pub fn route(attr: TokenStream, input: TokenStream) -> TokenStream {
    //  let combined = TokenStream::from_iter( vec![attr,item]);

    let input = parse_macro_input!(input as syn::ImplItemMethod);

    log(route_attribute_value(attr.to_string().as_str())).expect("valid route selector");

    //    attr.to_tokens().next();
    // we do this just to mem for a valid selector...
    //log(wrapped_route_selector(attr.tokens.to_string().as_str())).expect("properly formatted route selector");

    let params: Vec<FnArg> = input.sig.inputs.clone().into_iter().collect();
    let ctx = params
        .get(1)
        .expect("route expected InCtx<I,M> as first parameter");
    let ctx = messsage_ctx(ctx).expect("route expected InCtx<I,M> as first parameter");

    let __await = match input.sig.asyncness {
        None => quote! {},
        Some(_) => quote! {.await},
    };

    let root_ctx = match input.sig.asyncness {
        None => quote! {starlane::space::wave::exchange::synch::RootInCtx},
        Some(_) => quote! {starlane::space::wave::exchange::asynch::RootInCtx},
    };

    let in_ctx = match input.sig.asyncness {
        None => quote! {starlane::space::wave::exchange::synch::InCtx},
        Some(_) => quote! {starlane::space::wave::exchange::asynch::InCtx},
    };

    let __async = match input.sig.asyncness {
        None => quote! {},
        Some(_) => quote! {async},
    };

    let orig = input.sig.ident.clone();
    let ident = format_ident!("__{}__route", input.sig.ident);
    let rtn_type = rtn_type(&input.sig.output);
    let item = ctx.item;

    let expanded = quote! {
      #__async fn #ident( &self, mut ctx: #root_ctx ) -> starlane::space::wave::core::CoreBounce {
          let ctx: #in_ctx<'_,#item> = match ctx.push::<#item>() {
              Ok(ctx) => ctx,
              Err(err) => {
                    if ctx.wave.is_signal() {
                      return starlane::space::wave::core::CoreBounce::Absorbed;
                    }
                    else {
                      return starlane::space::wave::core::CoreBounce::Reflected(err.into());
                    }
              }
          };

          let result = self.#orig(ctx)#__await;
          #rtn_type
      }

      #input

    };

    //println!("{}", expanded.to_string());
    TokenStream::from(expanded)
}


pub(crate) enum Item {
    Request,
    RequestCore,
    Payload,
}

impl FromStr for Item {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "Request" => Ok(Item::Request),
            "RequestCore" => Ok(Item::RequestCore),
            "Payload" => Ok(Item::Payload),
            what => panic!("cannot convert Request to type '{}'", what),
        }
    }
}

pub(crate) struct RequestCtx {
    pub item: GenericArgument,
}

fn messsage_ctx(input: &FnArg) -> Result<RequestCtx, String> {
    if let FnArg::Typed(i) = input {
        if let Type::Path(path) = &*i.ty {
            if let PathArguments::AngleBracketed(generics) = &path
                .path
                .segments
                .last()
                .expect("expected last segment")
                .arguments
            {
                let mut args = generics.args.clone();
                let item = args
                    .pop()
                    .expect("expecting a generic for Context Item")
                    .into_value();

                let ctx = RequestCtx { item };

                return Ok(ctx);
            }
        }
    }
    Err("Parameter is not a RequestCtx".to_string())
}

fn rtn_type(output: &ReturnType) -> TokenStream2 {
    match output {
        ReturnType::Default => {
            quote! {starlane::space::wave::Bounce::Absorbed}
        }
        ReturnType::Type(_, path) => {
            if let Type::Path(path) = &**path {
                let PathSegment { ident, arguments } = path.path.segments.last().unwrap();
                match ident.to_string().as_str() {
                    "Result" => {
                        if let PathArguments::AngleBracketed(brackets) = arguments {
                            let arg = brackets.args.first().unwrap();
                            if "Substance" == arg.to_token_stream().to_string().as_str() {
                                quote! {
                                 use starlane::space::err::CoreReflector;
                                 match result {
                                     Ok(rtn) => starlane::space::wave::core::CoreBounce::Reflected(starlane::space::wave::core::ReflectedCore::ok_body(rtn)),
                                     Err(err) => starlane::space::wave::core::CoreBounce::Reflected(err.as_reflected_core())
                                 }
                                }
                            } else {
                                quote! {
                                 use starlane::space::err::CoreReflector;
                                 match result {
                                     Ok(rtn) => starlane::space::wave::core::CoreBounce::Reflected(rtn.into()),
                                     Err(err) => starlane::space::wave::core::CoreBounce::Reflected(err.as_reflected_core())
                                 }
                                }
                            }
                        } else {
                            panic!("Result without angle brackets")
                        }
                    }
                    "Bounce" => {
                        quote! {
                            let rtn : starlane::space::wave::core::CoreBounce = result.to_core_bounce();
                            rtn
                        }
                    }
                    "CoreBounce" => {
                        quote! {
                           result
                        }
                    }
                    "ReflectedCore" => {
                        quote! {
                           starlane::space::wave::core::CoreBounce::Reflected(result)
                        }
                    }
                    what => {
                        panic!("unknown return type: {}", what);
                    }
                }
            } else {
                panic!("expecting a path segment")
            }
        }
    }
}



struct RouteAttr {
    attribute: Attribute,
}

impl Parse for RouteAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let mut attribute = input.call(Attribute::parse_outer)?;
        Ok(RouteAttr {
            attribute: attribute.remove(0),
        })
    }
}


/// adds a trait to given struct or enum
#[proc_macro_derive(ToSpaceErr)]
pub fn to_space_err(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let ident = &input.ident;
    let rtn = quote! {
       impl starlane::space::err::ToSpaceErr for #ident {
            fn to_space_err(&self) -> starlane::space::err::SpaceErr {
                starlane::space::err::SpaceErr::to_space_err(&self.to_string())
            }
        }
    };
    rtn.into()
}