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
#![doc = include_str!("../README.md")]

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{quote, ToTokens};
use syn::{
    parenthesized,
    parse::{discouraged::Speculative, Parse, ParseStream},
    parse2,
    token::Paren,
    Error as SynError, Expr, Result as SynResult, Token,
};
use timrs_macro_utils::{
    error::unexpected_token_message,
    parse::{accumulate_while, LookaheadToken},
};

#[derive(Debug, PartialEq)]
enum OperatorToken {
    After,
    Before,
}

impl OperatorToken {
    fn resolve<F>(parsed: Self, lhs: F, rhs: F) -> impl FnOnce(TokenStream2) -> TokenStream2
    where
        F: FnOnce(TokenStream2) -> TokenStream2,
    {
        move |input| match parsed {
            Self::After => lhs(rhs(input)),
            Self::Before => rhs(lhs(input)),
        }
    }
}

impl Parse for OperatorToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        if input.peek(Token![<]) && input.peek2(Token![|]) {
            input.parse::<Token![<]>()?;
            input.parse::<Token![|]>()?;

            SynResult::Ok(Self::After)
        } else if input.peek(Token![|]) && input.peek2(Token![>]) {
            input.parse::<Token![|]>()?;
            input.parse::<Token![>]>()?;

            SynResult::Ok(Self::Before)
        } else {
            SynResult::Err(SynError::new(
                input.span(),
                unexpected_token_message("`Operator (<| or |>)`", &input.to_string()),
            ))
        }
    }
}

impl LookaheadToken for OperatorToken {
    const SIZE: usize = 2;
}

struct FunctionToken {
    value: Expr,
}

impl FunctionToken {
    fn resolve(parsed: Self) -> impl FnOnce(TokenStream2) -> TokenStream2 {
        move |input| {
            let value = parsed.value;

            quote! { (#value)(#input) }
        }
    }
}

impl Parse for FunctionToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        SynResult::Ok(Self {
            value: input.parse::<Expr>()?,
        })
    }
}

enum OperandToken {
    Function(FunctionToken),
    Operation(OperationToken),
    Parenthesized(Box<OperandToken>),
}

impl OperandToken {
    fn resolve(parsed: Self) -> impl FnOnce(TokenStream2) -> TokenStream2 {
        move |input| match parsed {
            Self::Function(value) => FunctionToken::resolve(value)(input),
            Self::Operation(value) => OperationToken::resolve(value)(input),
            Self::Parenthesized(value) => Self::resolve(*value)(input),
        }
    }
}

impl Parse for OperandToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        if input.peek(Paren) {
            let fork = input.fork();
            let content;

            parenthesized!(content in fork);

            if fork.is_empty() {
                input.advance_to(&fork);

                return content.parse::<Self>().map(Box::new).map(Self::Parenthesized);
            }
        }

        input.step(|cursor| {
            let mut is_operation = false;
            let (stream, next) = accumulate_while(*cursor, |current| {
                if !is_operation {
                    is_operation = OperatorToken::lookahead(current).is_ok();
                }

                !current.eof()
            })?;

            if is_operation {
                parse2::<OperationToken>(stream)
                    .map(Self::Operation)
                    .map(|value| (value, next))
            } else {
                parse2::<FunctionToken>(stream)
                    .map(Self::Function)
                    .map(|value| (value, next))
            }
        })
    }
}

struct OperationToken {
    lhs: Box<OperandToken>,
    operator: OperatorToken,
    rhs: Box<OperandToken>,
}

impl OperationToken {
    fn resolve(parsed: Self) -> impl FnOnce(TokenStream2) -> TokenStream2 {
        move |input| {
            OperatorToken::resolve(
                parsed.operator,
                OperandToken::resolve(*parsed.lhs),
                OperandToken::resolve(*parsed.rhs),
            )(input)
        }
    }
}

impl Parse for OperationToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        if input.peek(Paren) {
            let fork = input.fork();
            let content;

            parenthesized!(content in fork);

            if fork.is_empty() {
                input.advance_to(&fork);

                return content.parse::<Self>();
            }
        }

        input.step(|lhs_cursor| {
            let (lhs, operator_cursor) =
                accumulate_while(*lhs_cursor, |current| OperatorToken::lookahead(current).is_err())?;
            let (operator, rhs_cursor) = OperatorToken::lookahead(operator_cursor)?;
            let (rhs, next) = accumulate_while(rhs_cursor, |current| !current.eof())?;

            SynResult::Ok((
                Self {
                    lhs: parse2::<OperandToken>(lhs).map(Box::new)?,
                    operator,
                    rhs: parse2::<OperandToken>(rhs).map(Box::new)?,
                },
                next,
            ))
        })
    }
}

#[derive(Debug, PartialEq)]
struct InsertToken;

impl Parse for InsertToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        if input.peek(Token![-]) && input.peek2(Token![>]) && input.peek3(Token![>]) {
            input.parse::<Token![-]>()?;
            input.parse::<Token![>]>()?;
            input.parse::<Token![>]>()?;

            SynResult::Ok(Self {})
        } else {
            SynResult::Err(SynError::new(
                input.span(),
                unexpected_token_message("`Insert (->>)`", &input.to_string()),
            ))
        }
    }
}

impl LookaheadToken for InsertToken {
    const SIZE: usize = 3;
}

struct InputToken {
    value: Expr,
}

impl Parse for InputToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        input.step(|cursor| {
            let (stream, next) = accumulate_while(*cursor, |current| InsertToken::lookahead(current).is_err())?;

            parse2::<Expr>(stream).map(|value| (Self { value }, next))
        })
    }
}

struct PipeToken {
    input: InputToken,
    operation: OperationToken,
}

impl Parse for PipeToken {
    fn parse(input: ParseStream) -> SynResult<Self> {
        let input_token = input.parse::<InputToken>()?;
        input.parse::<InsertToken>()?;
        let operation_token = input.parse::<OperationToken>()?;

        SynResult::Ok(Self {
            input: input_token,
            operation: operation_token,
        })
    }
}

fn impl_pipe(tokens: TokenStream2) -> TokenStream2 {
    parse2::<PipeToken>(tokens).map_or_else(SynError::into_compile_error, |pipe_token| {
        OperationToken::resolve(pipe_token.operation)(pipe_token.input.value.to_token_stream())
    })
}

/// Macro providing the custom piping binary operators `before (|>)` and `after (<|)`, operations can be parenthesized and are left-associative.
///
/// # Examples
/// ## After Operator (`<|`):
/// ```
/// use timrs_pipe_macro::pipe;
///
/// fn increment(x: i32) -> i32 { x + 1 }
/// fn to_string(x: i32) -> String { x.to_string() }
/// fn greet(x: String) -> String { format!("HELLO {x}!") }
///
/// assert_eq!(
///     pipe! { 1 ->> greet <| to_string <| increment },
///     "HELLO 2!"
/// );
/// ```
///
/// ## Before Operator (`|>`):
///
/// ```
/// use timrs_pipe_macro::pipe;
///
/// fn increment(x: i32) -> i32 { x + 1 }
/// fn to_string(x: i32) -> String { x.to_string() }
/// fn greet(x: String) -> String { format!("HELLO {x}!") }
///
/// assert_eq!(
///     pipe! { 1 ->> increment |> to_string |> greet },
///     "HELLO 2!"
/// );
/// ```
///
/// # Grammar
/// The grammar rules for the `pipe!` macro are the following:
///
/// ## Tokens
/// ```text
/// e_e        := (end of input)
/// e_function := (any valid callable rust expression, i.e. can be called with the following syntax `f ()`)
/// e_input    := (any valid rust expression that can be used as a function input)
/// s_insert   := "->>"
/// s_p_left   := "("
/// s_p_right  := ")"
/// s_o_after  := "<|"
/// s_o_before := "|>"
/// ```
///
/// ## Rules
/// ```text
/// pipe                    := e_input s_insert operation e_e
/// operation               := parenthesized_operation | operand operator operand
/// parenthesized_operation := s_p_left operation s_p_right
/// operator                := s_o_after | s_o_before
/// operand                 := parenthesized_operand | operation | e_function
/// parenthesized_operand   := s_p_left operand s_p_right
/// ```
#[proc_macro]
pub fn pipe(tokens: TokenStream) -> TokenStream { impl_pipe(tokens.into()).into() }

#[cfg(test)]
mod tests {
    #[test]
    fn should_correctly_parse_after_operator_token() -> Result<(), String> {
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::OperatorToken;

        let expected = OperatorToken::After;
        let input = "<|";
        let output = parse_test::<OperatorToken>(build_tokens(input)).map_err(|error| error.to_string())?;

        assert_eq!(output, expected, "Testing `OperatorToken` successful parsing: `After`");

        Result::Ok(())
    }

    #[test]
    fn should_correctly_parse_before_operator_token() -> Result<(), String> {
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::OperatorToken;

        let expected = OperatorToken::Before;
        let input = "|>";
        let output = parse_test::<OperatorToken>(build_tokens(input)).map_err(|error| error.to_string())?;

        assert_eq!(output, expected, "Testing `OperatorToken` successful parsing: `Before`");

        Result::Ok(())
    }

    #[test]
    fn should_correctly_fail_parsing_operator_token() -> Result<(), String> {
        use timrs_macro_utils::{
            error::unexpected_token_message,
            test::{build_tokens, parse_test, pretty_print},
        };

        use super::OperatorToken;

        let expected_token = "`Operator (<| or |>)`";
        let got_token = "INVALID_INPUT";

        let expected = format!(
            "::core::compile_error!{{\"{}\"}}",
            unexpected_token_message(expected_token, got_token)
        );
        let input = got_token;
        let output = parse_test::<OperatorToken>(build_tokens(input)).unwrap_err();

        assert_eq!(
            pretty_print(output),
            pretty_print(build_tokens(&expected)),
            "Testing `OperatorToken` unsuccessful parsing"
        );

        Result::Ok(())
    }

    #[test]
    fn should_have_the_correct_lookahead_token_size_for_operator_token() {
        use timrs_macro_utils::parse::LookaheadToken;

        use super::OperatorToken;

        let expected = 2_usize;

        assert_eq!(OperatorToken::SIZE, expected)
    }

    #[test]
    fn should_correctly_parse_function_token() -> Result<(), String> {
        use quote::ToTokens;
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::FunctionToken;

        let input_closure = "| x | x + 1";
        let input_identifier = "a";
        let input_parenthesized = "(a)";
        let output_closure =
            parse_test::<FunctionToken>(build_tokens(input_closure)).map_err(|error| error.to_string())?;
        let output_identifier =
            parse_test::<FunctionToken>(build_tokens(input_identifier)).map_err(|error| error.to_string())?;
        let output_parenthesized =
            parse_test::<FunctionToken>(build_tokens(input_parenthesized)).map_err(|error| error.to_string())?;

        assert_eq!(
            output_closure.value.to_token_stream().to_string(),
            input_closure,
            "Testing `FunctionToken` successful parsing: Closure"
        );
        assert_eq!(
            output_identifier.value.to_token_stream().to_string(),
            input_identifier,
            "Testing `FunctionToken` successful parsing: Identifier"
        );
        assert_eq!(
            output_parenthesized.value.to_token_stream().to_string(),
            input_parenthesized,
            "Testing `FunctionToken` successful parsing: Parenthesized"
        );

        Result::Ok(())
    }

    #[test]
    fn should_correctly_fail_parsing_function_token() -> Result<(), String> {
        use quote::ToTokens;
        use timrs_macro_utils::test::{build_tokens, parse_test, pretty_print};

        use super::FunctionToken;

        let input_not_expression = "+";
        let output_not_expression = parse_test::<FunctionToken>(build_tokens(input_not_expression))
            .map(|value| value.value.to_token_stream().to_string())
            .unwrap_err();

        assert_eq!(
            pretty_print(output_not_expression),
            pretty_print(build_tokens("::core::compile_error!{\"expected an expression\"}")),
            "Testing `FunctionToken` unsuccessful parsing: Not an expression"
        );

        let input_eof = "";
        let output_eof = parse_test::<FunctionToken>(build_tokens(input_eof))
            .map(|value| value.value.to_token_stream().to_string())
            .unwrap_err();

        assert_eq!(
            pretty_print(output_eof),
            pretty_print(build_tokens(
                "::core::compile_error!{\"unexpected end of input, expected an expression\"}"
            )),
            "Testing `FunctionToken` unsuccessful parsing: End of file"
        );

        Result::Ok(())
    }

    #[test]
    fn should_correctly_parse_function_operand_token() -> Result<(), String> {
        use quote::ToTokens;
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::OperandToken;

        let input = "| x | x + 1";
        let output;

        if let OperandToken::Function(op) =
            parse_test::<OperandToken>(build_tokens(input)).map_err(|error| error.to_string())?
        {
            output = op.value.to_token_stream().to_string();
        } else {
            panic!("Unexpected `OperandToken` variant");
        }

        assert_eq!(output, input, "Testing `OperandToken` successful parsing: `Function`");

        Result::Ok(())
    }

    #[test]
    fn should_correctly_parse_operation_operand_token() -> Result<(), String> {
        use quote::ToTokens;
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::{OperandToken, OperatorToken};

        let operand = "| x | x + 1";

        let get_input = |operator: &str| -> String { format!("{operand} {operator} {operand}") };

        let after = "<|";
        let before = "|>";

        let expected_after = (operand.to_owned(), OperatorToken::After, operand.to_owned());
        let expected_before = (operand.to_owned(), OperatorToken::Before, operand.to_owned());
        let input_after = get_input(after);
        let input_before = get_input(before);
        let output_after;
        let output_before;

        if let OperandToken::Operation(op) =
            parse_test::<OperandToken>(build_tokens(&input_after)).map_err(|error| error.to_string())?
        {
            if let (OperandToken::Function(lhs), OperandToken::Function(rhs)) = (*op.lhs, *op.rhs) {
                output_after = (
                    lhs.value.to_token_stream().to_string(),
                    op.operator,
                    rhs.value.to_token_stream().to_string(),
                );
            } else {
                panic!("Incorrect `OperationToken`")
            }
        } else {
            panic!("Unexpected `OperandToken` variant");
        }

        if let OperandToken::Operation(op) =
            parse_test::<OperandToken>(build_tokens(&input_before)).map_err(|error| error.to_string())?
        {
            if let (OperandToken::Function(lhs), OperandToken::Function(rhs)) = (*op.lhs, *op.rhs) {
                output_before = (
                    lhs.value.to_token_stream().to_string(),
                    op.operator,
                    rhs.value.to_token_stream().to_string(),
                );
            } else {
                panic!("Incorrect `OperationToken`")
            }
        } else {
            panic!("Unexpected `OperandToken` variant");
        }

        assert_eq!(
            output_after, expected_after,
            "Testing `OperandToken` successful parsing: `OperationToken`"
        );
        assert_eq!(
            output_before, expected_before,
            "Testing `OperandToken` successful parsing: `OperationToken`"
        );

        Result::Ok(())
    }

    #[test]
    fn should_correctly_parse_parenthesized_operand_token() -> Result<(), String> {
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::OperandToken;

        let input = "(| x | x + 1)";

        if let OperandToken::Parenthesized(_) =
            parse_test::<OperandToken>(build_tokens(input)).map_err(|error| error.to_string())?
        {
            Result::Ok(())
        } else {
            panic!("Unexpected `OperandToken` variant");
        }
    }

    #[test]
    fn should_correctly_parse_insert_token() -> Result<(), String> {
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::InsertToken;

        let expected = InsertToken {};
        let input = "->>";
        let output = parse_test::<InsertToken>(build_tokens(input)).map_err(|error| error.to_string())?;

        assert_eq!(output, expected, "Testing `InsertToken` successful parsing");

        Result::Ok(())
    }

    #[test]
    fn should_correctly_fail_parsing_insert_token() -> Result<(), String> {
        use timrs_macro_utils::{
            error::unexpected_token_message,
            test::{build_tokens, parse_test, pretty_print},
        };

        use super::InsertToken;

        let expected_token = "`Insert (->>)`";
        let got_token = "INVALID_INPUT";

        let expected = format!(
            "::core::compile_error!{{\"{}\"}}",
            unexpected_token_message(expected_token, got_token)
        );
        let input = got_token;
        let output = parse_test::<InsertToken>(build_tokens(input)).unwrap_err();

        assert_eq!(
            pretty_print(output),
            pretty_print(build_tokens(&expected)),
            "Testing `InsertToken` unsuccessful parsing"
        );

        Result::Ok(())
    }

    #[test]
    fn should_have_the_correct_lookahead_token_size_for_insert_token() {
        use timrs_macro_utils::parse::LookaheadToken;

        use super::InsertToken;

        let expected = 3_usize;

        assert_eq!(InsertToken::SIZE, expected)
    }

    #[test]
    fn should_correctly_parse_input_token() -> Result<(), String> {
        use quote::ToTokens;
        use syn::{
            parse::{Parse, ParseStream},
            Result as SynResult,
        };
        use timrs_macro_utils::test::{build_tokens, parse_test};

        use super::{InputToken, InsertToken};

        #[derive(Debug, PartialEq)]
        struct Test {
            input_token: String,
            insert_token: InsertToken,
        }

        impl Parse for Test {
            fn parse(input: ParseStream) -> SynResult<Self> {
                SynResult::Ok(Self {
                    input_token: input
                        .parse::<InputToken>()
                        .map(|value| value.value.to_token_stream().to_string())?,
                    insert_token: input.parse::<InsertToken>()?,
                })
            }
        }

        fn get_input(expected: &str) -> String { format!("{expected} ->>") }

        let expected_block = "{ let x = 1 ; x }";
        let expected_identifier = "a";
        let expected_parenthesized = "(a)";
        let input_block = get_input(expected_block);
        let input_identifier = get_input(expected_identifier);
        let input_parenthesized = get_input(expected_parenthesized);
        let output_block = parse_test::<Test>(build_tokens(&input_block)).map_err(|error| error.to_string())?;
        let output_identifier =
            parse_test::<Test>(build_tokens(&input_identifier)).map_err(|error| error.to_string())?;
        let output_parenthesized =
            parse_test::<Test>(build_tokens(&input_parenthesized)).map_err(|error| error.to_string())?;

        assert_eq!(
            output_block.input_token, expected_block,
            "Testing `InputToken` successful parsing: Block"
        );
        assert_eq!(
            output_identifier.input_token, expected_identifier,
            "Testing `InputToken` successful parsing: Identifier"
        );
        assert_eq!(
            output_parenthesized.input_token, expected_parenthesized,
            "Testing `InputToken` successful parsing: Parenthesized"
        );

        Result::Ok(())
    }

    #[test]
    fn should_correctly_fail_parsing_input_token() -> Result<(), String> {
        use quote::ToTokens;
        use timrs_macro_utils::{
            error::unexpected_end_of_stream_message,
            test::{build_tokens, parse_test, pretty_print},
        };

        use super::InputToken;

        let input_not_expression = "+ ->>";
        let output_not_expression = parse_test::<InputToken>(build_tokens(input_not_expression))
            .map(|value| value.value.to_token_stream().to_string())
            .unwrap_err();

        assert_eq!(
            pretty_print(output_not_expression),
            pretty_print(build_tokens("::core::compile_error!{\"expected an expression\"}")),
            "Testing `InputToken` unsuccessful parsing: Not an expression"
        );

        let input_eof = "";
        let output_eof = parse_test::<InputToken>(build_tokens(input_eof))
            .map(|value| value.value.to_token_stream().to_string())
            .unwrap_err();

        assert_eq!(
            pretty_print(output_eof),
            pretty_print(build_tokens(&format!(
                "::core::compile_error!{{\"{}\"}}",
                unexpected_end_of_stream_message()
            ))),
            "Testing `InputToken` unsuccessful parsing: End of file"
        );

        Result::Ok(())
    }

    #[test]
    fn should_generate_correct_pipe_resolution_for_after() -> Result<(), String> {
        use timrs_macro_utils::test::build_tokens;

        use super::impl_pipe;

        fn get_simple_pipe(input: &str, operation: &str) -> String { format!("{input} ->> {operation}") }
        fn get_parenthesized_pipe(input: &str, operation: &str) -> String {
            get_simple_pipe(input, &format!("({operation})"))
        }

        let input = "1";

        let trivial_operation = "g <| f";
        let closure_operation = "|x| x.to_string() <| |x| x + 1";
        let associative_operation = "h <| g <| f";
        let compound_operation = "(i <| h) <| (g <| f)";

        let expected_trivial = "(g) ((f) (1))";
        let expected_closure = "(| x | x . to_string ()) ((| x | x + 1) (1))";
        let expected_associative = "(h) ((g) ((f) (1)))";
        let expected_compound = "(i) ((h) ((g) ((f) (1))))";
        let input_trivial_operation = get_simple_pipe(input, trivial_operation);
        let input_trivial_parenthesized_operation = get_parenthesized_pipe(input, trivial_operation);
        let input_closure_operation = get_simple_pipe(input, closure_operation);
        let input_closure_parenthesized_operation = get_parenthesized_pipe(input, closure_operation);
        let input_associative_operation = get_simple_pipe(input, associative_operation);
        let input_associative_parenthesized_operation = get_parenthesized_pipe(input, associative_operation);
        let input_compound_operation = get_simple_pipe(input, compound_operation);
        let input_compound_parenthesized_operation = get_parenthesized_pipe(input, compound_operation);

        assert_eq!(
            impl_pipe(build_tokens(&input_trivial_operation)).to_string(),
            build_tokens(expected_trivial).to_string(),
            "Testing `impl_pipe` `after` operation resolution: Trivial Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_trivial_parenthesized_operation)).to_string(),
            build_tokens(expected_trivial).to_string(),
            "Testing `impl_pipe` `after` operation resolution: Trivial Parenthesized Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_closure_operation)).to_string(),
            build_tokens(expected_closure).to_string(),
            "Testing `impl_pipe` `after` operation resolution: Closure Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_closure_parenthesized_operation)).to_string(),
            build_tokens(expected_closure).to_string(),
            "Testing `impl_pipe` `after` operation resolution: Closure Parenthesized Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_associative_operation)).to_string(),
            build_tokens(expected_associative).to_string(),
            "Testing `impl_pipe` `after` operation resolution: Associative Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_associative_parenthesized_operation)).to_string(),
            build_tokens(expected_associative).to_string(),
            "Testing `impl_pipe` `after` operation resolution: Associative Parenthesized Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_compound_operation)).to_string(),
            build_tokens(expected_compound).to_string(),
            "Testing `impl_pipe` `after` operation resolution: compound Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_compound_parenthesized_operation)).to_string(),
            build_tokens(expected_compound).to_string(),
            "Testing `impl_pipe` `after` operation resolution: compound Parenthesized Operation"
        );

        Result::Ok(())
    }

    #[test]
    fn should_generate_correct_pipe_resolution_for_before() -> Result<(), String> {
        use timrs_macro_utils::test::build_tokens;

        use super::impl_pipe;

        fn get_simple_pipe(input: &str, operation: &str) -> String { format!("{input} ->> {operation}") }
        fn get_parenthesized_pipe(input: &str, operation: &str) -> String {
            get_simple_pipe(input, &format!("({operation})"))
        }

        let input = "1";

        let trivial_operation = "f |> g";
        let closure_operation = "|x| x + 1 |> |x| x.to_string()";
        let associative_operation = "f |> g |> h";
        let compound_operation = "(f |> g) |> (h |> i)";

        let expected_trivial = "(g) ((f) (1))";
        let expected_closure = "(| x | x . to_string ()) ((| x | x + 1) (1))";
        let expected_associative = "(h) ((g) ((f) (1)))";
        let expected_compound = "(i) ((h) ((g) ((f) (1))))";
        let input_trivial_operation = get_simple_pipe(input, trivial_operation);
        let input_trivial_parenthesized_operation = get_parenthesized_pipe(input, trivial_operation);
        let input_closure_operation = get_simple_pipe(input, closure_operation);
        let input_closure_parenthesized_operation = get_parenthesized_pipe(input, closure_operation);
        let input_associative_operation = get_simple_pipe(input, associative_operation);
        let input_associative_parenthesized_operation = get_parenthesized_pipe(input, associative_operation);
        let input_compound_operation = get_simple_pipe(input, compound_operation);
        let input_compound_parenthesized_operation = get_parenthesized_pipe(input, compound_operation);

        assert_eq!(
            impl_pipe(build_tokens(&input_trivial_operation)).to_string(),
            build_tokens(expected_trivial).to_string(),
            "Testing `impl_pipe` `before` operation resolution: Trivial Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_trivial_parenthesized_operation)).to_string(),
            build_tokens(expected_trivial).to_string(),
            "Testing `impl_pipe` `before` operation resolution: Trivial Parenthesized Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_closure_operation)).to_string(),
            build_tokens(expected_closure).to_string(),
            "Testing `impl_pipe` `before` operation resolution: Closure Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_closure_parenthesized_operation)).to_string(),
            build_tokens(expected_closure).to_string(),
            "Testing `impl_pipe` `before` operation resolution: Closure Parenthesized Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_associative_operation)).to_string(),
            build_tokens(expected_associative).to_string(),
            "Testing `impl_pipe` `before` operation resolution: Associative Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_associative_parenthesized_operation)).to_string(),
            build_tokens(expected_associative).to_string(),
            "Testing `impl_pipe` `before` operation resolution: Associative Parenthesized Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_compound_operation)).to_string(),
            build_tokens(expected_compound).to_string(),
            "Testing `impl_pipe` `before` operation resolution: compound Operation"
        );
        assert_eq!(
            impl_pipe(build_tokens(&input_compound_parenthesized_operation)).to_string(),
            build_tokens(expected_compound).to_string(),
            "Testing `impl_pipe` `before` operation resolution: compound Parenthesized Operation"
        );

        Result::Ok(())
    }
}