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
//!
//! Defines `Union` struct and `generate_union` function to generate output of the `union!` macro based on input and given config.
//!

pub mod config;
pub mod name_constructors;

pub use config::Config;

use proc_macro2::TokenStream;
use quote::quote;
use quote::ToTokens;
use syn::parse::{Parse, ParseStream};
use syn::{parenthesized, Path};

use super::expr_chain::expr::{
    DefaultActionExpr, ExtractExpr, ProcessActionExpr, ProcessExpr, ReplaceExpr,
};
use super::expr_chain::utils::is_block_expr;
use super::expr_chain::{Chain, ExprChainWithDefault, ProcessWithDefault};
use super::handler::Handler;
use super::name_constructors::*;

///
/// Result of parsing `union!` macro input.
///
pub struct Union {
    pub futures_crate_path: Option<Path>,
    pub branches: Vec<ExprChainWithDefault>,
    pub handler: Option<Handler>,
}

mod keywords {
    syn::custom_keyword!(futures_crate_path);
}

///
/// Parser which takes expression chains and puts them into `branches` field,
/// and handler (one of `map`, `and_then`, `then`) and puts it into `handler` field.
/// Handler can be either defined once or not defined.
///
impl Parse for Union {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let mut union = Union {
            branches: Vec::new(),
            handler: None,
            futures_crate_path: None,
        };

        if input.peek(keywords::futures_crate_path) {
            input.parse::<keywords::futures_crate_path>()?;
            let content;
            parenthesized!(content in input);
            union.futures_crate_path = Some(content.parse()?);
        }

        while !input.is_empty() {
            if Handler::is_handler(&input) {
                if union.handler.is_some() {
                    return Err(input.error("Multiple `handler` cases found, only one allowed. Please, specify one of `map`, `and_then`, `then`."));
                }
                let handler = Handler::new(input)?.expect(
                    "union: Handler `is_handler` check failed. This's a bug, please report it.",
                );
                union.handler = Some(handler);
            } else {
                let expr_chain = ExprChainWithDefault::new(input, Box::new(Handler::is_handler))?;
                if let Some(expr_chain) = expr_chain {
                    union.branches.push(expr_chain)
                };
            };
        }

        if union.branches.is_empty() {
            Err(input.error("union must contain at least 1 branch."))
        } else {
            Ok(union)
        }
    }
}

fn expand_process_expr(
    previous_result: TokenStream,
    expr: &ProcessExpr,
    is_async: bool,
) -> TokenStream {
    match expr {
        ProcessExpr::Then(_) => {
            quote! { (#expr(#previous_result)) }
        }
        ProcessExpr::Inspect(expr) => {
            //
            // Define custom `into_token_stream` converter because `__inspect` function signature accepts two params.
            //
            let inspect_function_name = construct_inspect_function_name(is_async);
            quote! { #inspect_function_name(#expr, #previous_result) }
        }
        _ => {
            quote! { #previous_result#expr }
        }
    }
}

fn separate_block_expr<ExprType: ReplaceExpr + ExtractExpr + Clone>(
    inner_expr: &ExprType,
    step_number: impl Into<usize>,
    chain_index: impl Into<usize>,
) -> (TokenStream, ExprType) {
    let expr = inner_expr.extract_expr();
    if inner_expr.is_replaceable() && is_block_expr(expr) && step_number.into() > 0 {
        let wrapper_name = construct_result_wrapper_name(chain_index.into());
        if let Some(replaced) =
            inner_expr.replace_expr(syn::parse2(quote! { #wrapper_name }).unwrap())
        {
            return (quote! { let #wrapper_name = #expr; }, replaced);
        }
    }
    (quote! {}, inner_expr.clone())
}

///
/// Generates output of the `union!` macro based on parsed input and given config.
///
pub fn generate_union(
    Union {
        branches,
        handler,
        futures_crate_path,
    }: Union,
    Config { is_async, spawn }: Config,
) -> TokenStream {
    let futures_crate_path = if let Some(futures_crate_path) = futures_crate_path {
        if !is_async {
            panic!("futures_crate_path should be only provided for `async` `union!`")
        } else {
            futures_crate_path
        }
    } else {
        syn::parse2(quote! { ::futures }).unwrap()
    };

    let empty_stream = TokenStream::new();

    //
    // Total branch count.
    //
    let branch_count = branches.len();

    //
    // Spawn sync threads using `std::thread` module.
    //
    let sync_spawn = spawn && !is_async;

    //
    // Spawn async threads using `::tokio::spawn` from `tokio` crate.
    //

    let previous_result_handler: Box<dyn Fn(TokenStream) -> TokenStream> = if is_async {
        //
        // In case of async `union` we should wrap given result into a `Future`
        //
        Box::new(|value| quote! { { async move { #value } } })
    } else {
        //
        // Otherwise it will be enough to just use previous result.
        //
        Box::new(|value| quote! { #value })
    };

    let (
        //
        // Contains all chains depths. Used to calculate max length and determine if we reached chain's end and don't need to join branches anymore.
        //
        depths,
        //
        // `ProcessWithDefault` groups each of which represents chain of `Instant` actions but every next group is `Deferred` from previous.
        // [[map, or_else, map, and_then], [map, and_then]] =>
        // it will be interpreted as #expr.map().or_else.and_then() and after first step ends
        // #expr.map().and_then()
        //
        chains,
    ): (Vec<usize>, Vec<Vec<Vec<ProcessWithDefault>>>) = branches
        .iter()
        .map(|expr_chain| {
            expr_chain.get_members().iter().fold(
                (1usize, vec![Vec::new()]),
                |(depth, mut chain_acc), member| match &member.0 {
                    Some(ProcessActionExpr::Deferred(_)) => match member.1 {
                        Some(DefaultActionExpr::Instant(_)) | None => {
                            chain_acc.push(vec![member.clone()]);
                            (depth + 1, chain_acc)
                        }
                        Some(DefaultActionExpr::Deferred(_)) => {
                            chain_acc.push(vec![ProcessWithDefault(member.0.clone(), None)]);
                            chain_acc.push(vec![ProcessWithDefault(None, member.1.clone())]);
                            (depth + 2, chain_acc)
                        }
                    },
                    _ => match &member.1 {
                        Some(DefaultActionExpr::Instant(_)) | None => {
                            chain_acc.last_mut().unwrap().push(member.clone());
                            (depth, chain_acc)
                        }
                        Some(DefaultActionExpr::Deferred(_)) => {
                            chain_acc
                                .last_mut()
                                .unwrap()
                                .push(ProcessWithDefault(member.0.clone(), None));
                            chain_acc.push(vec![ProcessWithDefault(None, member.1.clone())]);
                            (depth + 1, chain_acc)
                        }
                    },
                },
            )
        })
        .unzip();

    //
    // Returns `Pat` name if exists, otherwise generate default chain result name.
    //
    let get_chain_result_name = |chain_index: usize| -> TokenStream {
        branches[chain_index]
            .get_pat()
            .as_ref()
            .map(|pat| quote! { #pat })
            .unwrap_or_else(|| {
                let name = construct_result_name(chain_index);
                name.into_token_stream()
            })
    };

    //
    // Calculates max chain depth.
    //
    let max_depth = *depths.iter().max().unwrap_or(&0) + (sync_spawn as usize);

    //
    // Contains all generated code to be executed step by step before final results.
    //
    let mut results_by_step = Vec::new();

    for step_number in 0..max_depth {
        if step_number > 0 {
            //
            // If we already have tuple of results, deconstruct them before use in order to every result could be captured by its chain closure correclty.
            //
            let previous_step_result_name = construct_step_result_name(step_number - 1);
            let results: Vec<_> = (0..branch_count)
                .map(|chain_index| {
                    let result_name = get_chain_result_name(chain_index);
                    quote! { #result_name }
                })
                .collect();

            results_by_step.push(if sync_spawn {
                let results_joiners = results.iter().enumerate().map(|(chain_index, result)| {
                    if depths[chain_index] >= step_number {
                        quote! { #result.join().unwrap() }
                    } else {
                        quote! { #result }
                    }
                });
                quote! {
                    let (#( #results ),*) = #previous_step_result_name;
                    let (#( #results ),*) = (#( #results_joiners ),*);
                }
            } else {
                quote! {
                    let (#( #results ),*) = #previous_step_result_name;
                }
            });
        }

        let (def_exprs, step_exprs): (Vec<_>, Vec<_>) = 
            chains
                .iter()
                .map(|chain| chain.get(step_number as usize))
                .enumerate()
                .map(|(chain_index, chain_step_actions)| match chain_step_actions {
                    Some(chain) => chain
                        .iter()
                        .fold(None, |acc, ProcessWithDefault(expr, default_expr)| {
                            let or_clause = 
                                default_expr
                                    .as_ref()
                                    .map(ExtractExpr::extract_inner_expr)
                                    .map(|expr| expr.into_token_stream())
                                    .unwrap_or_else(|| empty_stream.clone());
                            acc.map(
                                |(previous_def_expr, previous_result)| 
                                    match &expr {
                                        Some(ProcessActionExpr::Instant(process_expr)) => {
                                            let (def_expr, process_expr) = separate_block_expr(process_expr, step_number, chain_index);
                                            let process_expr = expand_process_expr(previous_result, &process_expr, is_async);
                                            (quote!{ #previous_def_expr #def_expr }, quote! { #process_expr#or_clause })
                                        }
                                        None => {
                                            let default_expr = default_expr.as_ref().unwrap().clone();
                                            let (def_expr, or_clause) = separate_block_expr(default_expr.extract_inner_expr(), step_number, chain_index);
                                            (quote!{ #previous_def_expr #def_expr }, quote! { #previous_result#or_clause })
                                        }
                                        _ => panic!("union: Unexpected expression type. This is a bug, please report it."),
                                    }
                            )
                            .or_else(|| 
                                Some(
                                    match expr {
                                        Some(ProcessActionExpr::Deferred(process_expr)) => {
                                            let previous_result_name = get_chain_result_name(chain_index);
                                            let previous_result = previous_result_handler(quote! { #previous_result_name });
                                            let (def_expr, process_expr) = separate_block_expr(process_expr, step_number, chain_index);
                                            let process_expr = expand_process_expr(previous_result, &process_expr, is_async);
                                            (def_expr, quote! { #process_expr#or_clause })
                                        }
                                        Some(ProcessActionExpr::Instant(process_expr)) => {
                                            let (def_expr, process_expr) = separate_block_expr(process_expr, step_number, chain_index);
                                            (def_expr, quote! { #process_expr#or_clause })
                                        }
                                        None => {
                                            let previous_result_name = get_chain_result_name(chain_index);
                                            let previous_result = previous_result_handler(quote! { #previous_result_name });
                                            let default_expr = default_expr.as_ref().unwrap().clone();
                                            let (def_expr, or_clause) = separate_block_expr(default_expr.extract_inner_expr(), step_number, chain_index);
                                            (def_expr, quote! { #previous_result#or_clause })
                                        }
                                    }
                                )
                            )
                        })
                        .map(|(def_expr, chain)|
                            (
                                def_expr,
                                if spawn {
                                    if is_async {
                                        let spawn_tokio_function_name = construct_spawn_tokio_function_name();
                                        quote! {
                                            { #spawn_tokio_function_name(#chain) }
                                        }
                                    } else {
                                        let thread_builder_name = construct_thread_builder_name(chain_index);
                                        quote! {
                                            { #thread_builder_name.spawn(move || #chain ).unwrap() }
                                        }
                                    }
                                } else {
                                    quote! { #chain }
                                }
                            )
                        )
                        .unwrap_or_else(|| (empty_stream.clone(), empty_stream.clone())),
                    None => {
                        let previous_result_name = get_chain_result_name(chain_index);
                        (empty_stream.clone(), previous_result_handler(quote! { #previous_result_name }))
                    }
                })
                .unzip();

        //
        // Name of variable which contains tuple of current step results.
        //
        let step_result_name = construct_step_result_name(step_number);

        results_by_step.push(if is_async {
            quote! {
                #(#def_exprs)*
                let #step_result_name = #futures_crate_path::join!(#( #step_exprs ),*);
            }
        } else {
            //
            // In case of sync spawn generate thread builder for every chain.
            //
            let thread_builders = if spawn {
                (0..branch_count)
                    .map(|chain_index| {
                        let thread_name = construct_thread_name(chain_index).to_string();
                        let thread_builder_name = construct_thread_builder_name(chain_index);
                        quote! {
                            let #thread_builder_name = ::std::thread::Builder::new();
                            let #thread_builder_name = #thread_builder_name.name(
                                ::std::thread::current().name()
                                    .map(
                                        |current_thread_name|
                                            format!("{current_thread_name}_{new_thread_name}",
                                                current_thread_name=current_thread_name,
                                                new_thread_name=#thread_name
                                            )
                                    )
                                    .unwrap_or(#thread_name.to_owned())

                            );
                        }
                    })
                    .collect()
            } else {
                Vec::new()
            };
            quote! {
                #( #thread_builders );*
                #(#def_exprs)*
                let #step_result_name = (#( #step_exprs ),*);
            }
        });
    }

    let last_step_results = construct_step_result_name(max_depth - 1);

    //
    // Return last step results at the end of expression.
    //
    let results = quote! { { #( #results_by_step )* #last_step_results } };

    //
    // Define variable names to be used when destructuring results.
    //
    let result_vars: Vec<_> = (0..branch_count)
        .map(|index| {
            let result_name = construct_result_name(index);
            quote! { #result_name }
        })
        .collect();

    //
    // Will transpose tuple of results in result of tuple.
    //
    // (Result<A, Error>, Result<B, Error>, Result<C, Error>) => Result<(A, B, C), Error>
    //
    // ```
    // result0.and_then(|value0| result1.and_then(|value1| result2.map(|value2| (value0, value1, value2))))
    // ```
    //
    //
    let generate_results_unwrapper = || {
        (0..branch_count).fold(None, |acc, index| {
            let index = branch_count - index - 1;
            let value_var_name = construct_var_name(index);
            let result_var_name = construct_result_name(index);
            acc.and_then(|acc| Some(quote! { #result_var_name.and_then(|#value_var_name| #acc ) }))
                .or_else(|| {
                    //
                    // Generates final tuple of unwrapped results.
                    //
                    let tuple_values = (0..branch_count).map(|index| {
                        let value_var_name = construct_var_name(index);
                        quote! { #value_var_name }
                    });
                    Some(quote! { #result_var_name.map(|#value_var_name| (#( #tuple_values ),*) ) })
                })
        })
    };

    let results_wrapper = if is_async {
        quote! { async move { __results } }
    } else {
        quote! { __results }
    };

    //
    // Defines handler based on user input or returns result of tuple of values
    // [or single result in case of one branch].
    //
    let handle_results = handler.as_ref().map_or_else(
        || {
            let unwrap_results = generate_results_unwrapper();
            if branch_count == 1 && is_async {
                //
                // Return first tuple element if have one branch
                //
                quote! {
                    __results.0
                }
            } else {
                //
                // Transform tuple of results in result of tuple
                //
                quote! {
                    let (#( #result_vars ),*) = __results;
                    let __results = #unwrap_results;
                    __results
                }
            }
        },
        |handler| match handler {
            Handler::Then(handler) => {
                //
                // Don't unwrap results because handler accepts results.
                //
                quote! {
                    let __handler = #handler;
                    let (#( #result_vars ),*) = __results;
                    __handler(#( #result_vars ),*)
                }
            }
            Handler::Map(handler) => {
                //
                // Unwrap results and pass them to handler if all of them are `Ok` (`Some`). Otherwise return `Err` (`None`).
                //
                let unwrap_results = generate_results_unwrapper();

                if !is_async {
                    quote! {
                        let (#( #result_vars ),*) = __results;
                        let __results = #unwrap_results;
                        #results_wrapper.map(|__results| {
                            let __handler = #handler;
                            let (#( #result_vars ),*) = __results;
                            __handler(#( #result_vars ),*)
                        })
                    }
                } else {
                    quote! {
                        let (#( #result_vars ),*) = __results;
                        let __results = #unwrap_results;
                        #results_wrapper.map(|__results| {
                            __results.map(|__results| {
                                let __handler = #handler;
                                let (#( #result_vars ),*) = __results;
                                __handler(#( #result_vars ),*)
                            })
                        })
                    }
                }
            }
            Handler::AndThen(handler) => {
                //
                // Unwrap results and pass them to handler if all of them are `Ok` (`Some`). Otherwise return `Err` (`None`).
                //
                let unwrap_results = generate_results_unwrapper();

                quote! {
                    let (#( #result_vars ),*) = __results;
                    let __results = #unwrap_results;
                    #results_wrapper.and_then(|__results| {
                        let __handler = #handler;
                        let (#( #result_vars ),*) = __results;
                        __handler(#( #result_vars ),*)
                    })
                }
            }
        },
    );

    let inspect_function_name = construct_inspect_function_name(is_async);
    let inspect_definition = if is_async {
        quote! {
            fn #inspect_function_name<T, I: #futures_crate_path::future::Future<Output = T>>(handler: impl Fn(&T) -> (), input: I) -> impl #futures_crate_path::future::Future<Output = T> {
                input.inspect(handler)
            }
        }
    } else {
        quote! {
            fn #inspect_function_name<I>(handler: impl Fn(&I) -> (), input: I) -> I {
                handler(&input);
                input
            }
        }
    };

    if is_async {
        let async_spawn_fn_definition = if spawn {
            let spawn_tokio_function_name = construct_spawn_tokio_function_name();
            quote! {
                async fn #spawn_tokio_function_name<T, F: #futures_crate_path::future::Future<Output = T>>(future: F) -> T
                where
                    F: Send + Sync + 'static,
                    T: Send + Sync + 'static,
                {
                    let (tx, rx) = #futures_crate_path::channel::oneshot::channel();

                    ::tokio::spawn(async move {
                        let value = future.await;
                        tx.send(value).unwrap_or_else(|_| panic!("Unexpected futures ::channel::oneshot::channel panic"));
                    });

                    rx.await.unwrap_or_else(|_| panic!("Unexpected futures ::channel::oneshot::channel panic"))
                }
            }
        } else {
            empty_stream.clone()
        };
        let await_handler = if handler.is_some() {
            quote! { .await }
        } else {
            empty_stream.clone()
        };
        quote! {
            async move {
                use #futures_crate_path::{FutureExt, TryFutureExt, StreamExt, TryStreamExt};
                #async_spawn_fn_definition
                #inspect_definition
                let __results = #results;
                #handle_results#await_handler
            }
        }
    } else {
        quote! {{
            #inspect_definition
            let __results = #results;
            #handle_results
        }}
    }
}