1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
//! Procedural macros for the [`fp-library`](https://docs.rs/fp-library/latest/fp_library/) crate.
//!
//! This crate provides macros for generating and working with Higher-Kinded Type (HKT) traits.
pub // Applicative do-notation
pub // Type and trait analysis
pub // Code generation (includes re-exports)
pub // Core infrastructure (config, error, result)
pub // Documentation generation macros
pub // Higher-Kinded Type macros
pub // Hindley-Milner type conversion
pub // Monadic do-notation
pub // Type resolution
pub // Support utilities (attributes, syntax, validation, errors)
use ;
/// Generates the name of a `Kind` trait based on its signature.
///
/// This macro takes a list of associated type definitions, similar to a trait definition.
///
/// ### Syntax
///
/// ```ignore
/// Kind!(
/// type AssocName<Params>: Bounds;
/// // ...
/// )
/// ```
///
/// * `Associated Types`: A list of associated type definitions (e.g., `type Of<T>;`) that define the signature of the Kind.
///
/// ### Generates
///
/// The name of the generated `Kind` trait (e.g., `Kind_0123456789abcdef`).
/// The name is deterministic and based on a hash of the signature.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// let name = Kind!(type Of<T>;);
///
/// // Expanded code
/// let name = Kind_...; // e.g., Kind_a1b2c3d4e5f67890
/// ```
///
/// ```ignore
/// // Invocation
/// let name = Kind!(type Of<'a, T: Display>: Debug;);
///
/// // Expanded code
/// let name = Kind_...; // Unique hash based on signature
/// ```
///
/// ```ignore
/// // Invocation
/// let name = Kind!(
/// type Of<T>;
/// type SendOf<T>: Send;
/// );
///
/// // Expanded code
/// let name = Kind_...; // Unique hash based on signature
/// ```
///
/// ### Limitations
///
/// Due to Rust syntax restrictions, this macro cannot be used directly in positions where a
/// concrete path is expected by the parser, such as:
/// * Supertrait bounds: `trait MyTrait: Kind!(...) {}` (Invalid)
/// * Type aliases: `type MyKind = Kind!(...);` (Invalid)
/// * Trait aliases: `trait MyKind = Kind!(...);` (Invalid)
///
/// For supertrait bounds, use the [`kind`] attribute macro instead:
/// ```ignore
/// #[kind(type Of<'a, A: 'a>: 'a;)]
/// pub trait Functor { ... }
/// ```
///
/// For other positions, you must use the generated name directly (e.g., `Kind_...`).
/// Defines a new `Kind` trait and its corresponding `InferableBrand` trait.
///
/// This macro generates a trait definition for a Higher-Kinded Type signature,
/// along with a `InferableBrand` trait that enables closure-directed brand inference
/// in dispatch functions (see [`crate::dispatch`](https://docs.rs/fp-library/latest/fp_library/dispatch/)).
///
/// ### Syntax
///
/// ```ignore
/// trait_kind!(
/// type AssocName<Params>: Bounds;
/// // ...
/// )
/// ```
///
/// * `Associated Types`: A list of associated type definitions (e.g., `type Of<T>;`) that define the signature of the Kind.
///
/// ### Generates
///
/// Two public trait definitions with unique names derived from the signature:
///
/// 1. `Kind_{hash}`: The HKT trait with the specified associated types.
/// 2. `InferableBrand_{hash}`: A reverse-mapping trait for closure-directed brand inference.
/// Both share the same content hash.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// trait_kind!(type Of<T>;);
///
/// // Expanded code
/// pub trait Kind_a1b2... {
/// type Of<T>;
/// }
/// pub trait InferableBrand_a1b2...<A> {
/// type Marker;
/// }
/// ```
///
/// ```ignore
/// // Invocation
/// trait_kind!(type Of<'a, T: Display>: Debug;);
///
/// // Expanded code
/// pub trait Kind_cdef... {
/// type Of<'a, T: Display>: Debug;
/// }
/// pub trait InferableBrand_cdef...<'a, Brand, A: Display> {
/// type Marker;
/// }
/// ```
/// Implements a `Kind` trait and its `InferableBrand` trait for a brand.
///
/// This macro simplifies the implementation of a generated `Kind` trait for a specific
/// brand type, and also generates the `InferableBrand` impl that enables closure-directed brand
/// inference in dispatch functions. It infers the correct `Kind` trait to implement based
/// on the signature of the associated types provided in the block.
///
/// The signature (names, parameters, and bounds) of the associated types must match
/// the definition used in [`trait_kind!`] or [`Kind!`] to ensure the correct trait is implemented.
///
/// ### Syntax
///
/// ```ignore
/// impl_kind! {
/// // Optional impl generics
/// impl<Generics> for BrandType
/// // Optional where clause
/// where Bounds
/// {
/// type AssocName<Params> = ConcreteType;
/// // ... more associated types
/// }
/// }
/// ```
///
/// * `Generics`: Optional generic parameters for the implementation.
/// * `BrandType`: The brand type to implement the Kind for.
/// * `Bounds`: Optional where clause bounds.
/// * `Associated Types`: The associated type assignments (e.g., `type Of<A> = Option<A>;`).
///
/// ### Generates
///
/// 1. An implementation of the appropriate `Kind_{hash}` trait for the brand.
/// 2. A `InferableBrand_{hash}` impl for the target type with `type Marker = Val`,
/// enabling closure-directed brand inference for both single-brand and
/// multi-brand types.
///
/// The `InferableBrand` impl is generated for ALL brands (including multi-brand types).
/// Projection types and multiple-associated-type definitions do suppress it.
///
/// ### Attributes
///
/// Inside the `impl_kind!` block, you can use these attributes:
///
/// * `#[multi_brand]`: Marks this brand as sharing its target type with other
/// brands. Does NOT suppress `InferableBrand` impl generation.
/// * `#[document_default]`: Marks this associated type as the default for resolving bare `Self` in
/// the generated documentation for this brand within the module.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// impl_kind! {
/// for OptionBrand {
/// #[document_default]
/// type Of<A> = Option<A>;
/// }
/// }
///
/// // Expanded code (Kind impl + InferableBrand impl)
/// impl Kind_a1b2... for OptionBrand {
/// type Of<A> = Option<A>;
/// }
/// impl<A> InferableBrand_a1b2...<OptionBrand, A> for Option<A> {
/// type Marker = Val;
/// }
/// ```
///
/// ```ignore
/// // Invocation with impl generics
/// impl_kind! {
/// impl<E> for ResultBrand<E> {
/// type Of<A> = Result<A, E>;
/// }
/// }
///
/// // Expanded code
/// impl<E> Kind_... for ResultBrand<E> {
/// type Of<A> = Result<A, E>;
/// }
/// impl<A, E> InferableBrand_...<ResultBrand<E>, A> for Result<A, E> {
/// type Marker = Val;
/// }
/// ```
///
/// ```ignore
/// // Multi-brand type: InferableBrand still generated
/// impl_kind! {
/// #[multi_brand]
/// impl<E> for ResultErrAppliedBrand<E> {
/// type Of<'a, A: 'a>: 'a = Result<A, E>;
/// }
/// }
///
/// // Expanded code (Kind impl + InferableBrand impl)
/// impl<E> Kind_... for ResultErrAppliedBrand<E> {
/// type Of<'a, A: 'a>: 'a = Result<A, E>;
/// }
/// impl<'a, A: 'a, E> InferableBrand_...<'a, ResultErrAppliedBrand<E>, A>
/// for Result<A, E>
/// {
/// type Marker = Val;
/// }
/// ```
///
/// ```ignore
/// // Multiple associated types: InferableBrand skipped automatically
/// impl_kind! {
/// impl<E> for MyBrand<E> where E: Clone {
/// type Of<A> = MyType<A, E>;
/// type SendOf<A> = MySendType<A, E>;
/// }
/// }
///
/// // Expanded code (only Kind impl)
/// impl<E> Kind_... for MyBrand<E> where E: Clone {
/// type Of<A> = MyType<A, E>;
/// type SendOf<A> = MySendType<A, E>;
/// }
/// ```
/// Applies a brand to type arguments.
///
/// This macro projects a brand type to its concrete type using the appropriate
/// `Kind` trait. It uses a syntax that mimics a fully qualified path, where the
/// `Kind` trait is specified by its signature.
///
/// ### Syntax
///
/// ```ignore
/// Apply!(<Brand as Kind!( KindSignature )>::AssocType<Args>)
/// ```
///
/// * `Brand`: The brand type (e.g., `OptionBrand`).
/// * `KindSignature`: A list of associated type definitions defining the `Kind` trait schema.
/// * `AssocType`: The associated type to project (e.g., `Of`).
/// * `Args`: The concrete arguments to apply.
///
/// ### Generates
///
/// The concrete type resulting from applying the brand to the arguments.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// // Applies MyBrand to lifetime 'static and type String.
/// type Concrete = Apply!(<MyBrand as Kind!( type Of<'a, T>; )>::Of<'static, String>);
///
/// // Expanded code
/// type Concrete = <MyBrand as Kind_...>::Of<'static, String>;
/// ```
///
/// ```ignore
/// // Invocation
/// // Applies MyBrand to a generic type T with bounds.
/// type Concrete = Apply!(<MyBrand as Kind!( type Of<T: Clone>; )>::Of<T>);
///
/// // Expanded code
/// type Concrete = <MyBrand as Kind_...>::Of<T>;
/// ```
///
/// ```ignore
/// // Invocation
/// // Complex example with lifetimes, types, and output bounds.
/// type Concrete = Apply!(<MyBrand as Kind!( type Of<'a, T: Clone + Debug>: Display; )>::Of<'a, T>);
///
/// // Expanded code
/// type Concrete = <MyBrand as Kind_...>::Of<'a, T>;
/// ```
///
/// ```ignore
/// // Invocation
/// // Use a custom associated type for projection.
/// type Concrete = Apply!(<MyBrand as Kind!( type Of<T>; type SendOf<T>; )>::SendOf<T>);
///
/// // Expanded code
/// type Concrete = <MyBrand as Kind_...>::SendOf<T>;
/// ```
/// Adds a `Kind` supertrait bound to a trait definition.
///
/// This attribute macro parses a Kind signature and adds the corresponding
/// `Kind_` trait as a supertrait bound, avoiding the need to reference
/// hash-based trait names directly.
///
/// ### Syntax
///
/// ```ignore
/// #[kind(type AssocName<Params>: Bounds;)]
/// pub trait MyTrait {
/// // ...
/// }
/// ```
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[kind(type Of<'a, A: 'a>: 'a;)]
/// pub trait Functor {
/// fn map<'a, A: 'a, B: 'a>(
/// f: impl Fn(A) -> B + 'a,
/// fa: Apply!(<Self as Kind!(type Of<'a, T: 'a>: 'a;)>::Of<'a, A>),
/// ) -> Apply!(<Self as Kind!(type Of<'a, T: 'a>: 'a;)>::Of<'a, B>);
/// }
///
/// // Expanded code
/// pub trait Functor: Kind_cdc7cd43dac7585f {
/// // body unchanged
/// }
/// ```
///
/// ```ignore
/// // Works with existing supertraits
/// #[kind(type Of<'a, A: 'a>: 'a;)]
/// pub trait Monad: Applicative {
/// // Kind_ bound is appended: Monad: Applicative + Kind_...
/// }
/// ```
/// Generates re-exports for all public free functions in a directory.
///
/// This macro scans the specified directory for Rust files, parses them to find public free functions,
/// and generates `pub use` statements for them. It supports aliasing to resolve name conflicts
/// and exclusions to suppress specific functions from being re-exported.
///
/// ### Syntax
///
/// ```ignore
/// generate_function_re_exports!("path/to/directory", {
/// "module::name": aliased_name,
/// ...
/// }, exclude {
/// "module::name",
/// ...
/// })
/// ```
///
/// * `path/to/directory`: The path to the directory containing the modules, relative to the crate root.
/// * `aliases` (optional): A map of function names to their desired aliases. Keys can be
/// qualified (`"module::function"`) or unqualified (`"function"`). When aliased, the function
/// is exported under the alias name only.
/// * `exclude` (optional): A set of function names to suppress entirely. Keys use the same
/// qualified/unqualified format as aliases. Excluded functions are not re-exported at all,
/// but remain available in their original modules.
///
/// ### Generates
///
/// `pub use` statements for each public function found in the directory, except those
/// listed in the `exclude` block.
///
/// ### Examples
///
/// ```ignore
/// generate_function_re_exports!("src/classes", {
/// "category::identity": category_identity,
/// "filterable::filter": filterable_filter,
/// }, exclude {
/// "ref_filterable::ref_filter",
/// "ref_filterable::ref_filter_map",
/// });
///
/// // Expanded: re-exports all public functions except ref_filter and ref_filter_map.
/// // category::identity is exported as category_identity.
/// // filterable::filter is exported as filterable_filter.
/// ```
/// Generates re-exports for all public traits in a directory.
///
/// This macro scans the specified directory for Rust files, parses them to find public traits,
/// and generates `pub use` statements for them. Supports the same aliasing and exclusion
/// syntax as [`generate_function_re_exports!`].
///
/// ### Syntax
///
/// ```ignore
/// generate_trait_re_exports!("path/to/directory", {
/// "module::TraitName": AliasedName,
/// ...
/// }, exclude {
/// "module::TraitName",
/// ...
/// })
/// ```
///
/// * `path/to/directory`: The path to the directory containing the modules, relative to the crate root.
/// * `aliases` (optional): A map of trait names to their desired aliases.
/// * `exclude` (optional): A set of trait names to suppress from re-export.
///
/// ### Generates
///
/// `pub use` statements for each public trait found in the directory, except those
/// listed in the `exclude` block.
///
/// ### Examples
///
/// ```ignore
/// generate_trait_re_exports!("src/classes", {});
///
/// // Expanded code
/// pub use src::classes::functor::Functor;
/// pub use src::classes::monad::Monad;
/// // ... other re-exports
/// ```
/// Generates a Hindley-Milner style type signature for a function.
///
/// This macro analyzes the function signature and generates a documentation comment
/// containing the corresponding Hindley-Milner type signature.
///
/// When used within a module annotated with [`#[document_module]`](macro@document_module),
/// it automatically resolves `Self` and associated types based on the module's projection map.
///
/// ### Syntax
///
/// ```ignore
/// // Auto-generate from the function signature
/// #[document_signature]
/// pub fn function_name<Generics>(params) -> ReturnType { ... }
///
/// // Manual override with an explicit signature string
/// #[document_signature("forall A B. (A -> B) -> A -> B")]
/// pub fn function_name<Generics>(params) -> ReturnType { ... }
/// ```
///
/// When a string argument is provided, it is emitted directly as the
/// signature without any analysis. This is useful for functions whose
/// signatures cannot be inferred automatically.
///
/// When applying this macro to a method inside a trait, you can provide the trait name
/// as an argument to correctly generate the `Trait self` constraint.
///
/// ### Generates
///
/// A documentation comment with the generated signature, prepended to the function definition.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[document_signature]
/// pub fn map<F: Functor, A, B>(f: impl Fn(A) -> B, fa: F::Of<A>) -> F::Of<B> { ... }
///
/// // Expanded code
/// /// ### Type Signature
/// /// `forall f a b. Functor f => (a -> b, f a) -> f b`
/// pub fn map<F: Functor, A, B>(f: impl Fn(A) -> B, fa: F::Of<A>) -> F::Of<B> { ... }
/// ```
///
/// ```ignore
/// // Invocation
/// #[document_signature]
/// pub fn foo(x: impl Iterator<Item = String>) -> i32 { ... }
///
/// // Expanded code
/// /// ### Type Signature
/// /// `iterator -> i32`
/// pub fn foo(x: impl Iterator<Item = String>) -> i32 { ... }
/// ```
///
/// ```ignore
/// // Invocation
/// trait Functor {
/// #[document_signature]
/// fn map<A, B>(f: impl Fn(A) -> B, fa: Self::Of<A>) -> Self::Of<B>;
/// }
///
/// // Expanded code
/// trait Functor {
/// /// ### Type Signature
/// /// `forall self a b. Functor self => (a -> b, self a) -> self b`
/// fn map<A, B>(f: impl Fn(A) -> B, fa: Self::Of<A>) -> Self::Of<B>;
/// }
/// ```
///
/// Manual override:
///
/// ```ignore
/// // Invocation
/// #[document_signature("forall F A B. Contravariant F => (B -> A, F A) -> F B")]
/// pub fn contramap<FA, A, B>(f: impl Fn(B) -> A, fa: FA) -> FA::Of<B> { ... }
///
/// // Expanded code
/// /// ### Type Signature
/// /// `forall F A B. Contravariant F => (B -> A, F A) -> F B`
/// pub fn contramap<FA, A, B>(f: impl Fn(B) -> A, fa: FA) -> FA::Of<B> { ... }
/// ```
///
/// ### Dispatch-aware generation
///
/// When used inside a module annotated with
/// [`#[document_module]`](macro@document_module), this macro benefits
/// from dispatch trait analysis. If the function references a dispatch
/// trait (via `impl *Dispatch<...>` or a where-clause bound), the
/// macro builds a synthetic signature that replaces dispatch machinery
/// with semantic equivalents (branded types, closure arrows, type
/// class constraints). This produces cleaner signatures like
/// `forall Brand A B. Functor Brand => (A -> B, Brand A) -> Brand B`
/// instead of the raw Rust signature with `InferableBrand` and `Kind_*` bounds.
///
/// ### Configuration
///
/// This macro can be configured via `Cargo.toml` under `[package.metadata.document_signature]`.
///
/// * `brand_mappings`: A map of brand struct names to their display names in the signature.
/// * `apply_macro_aliases`: A list of macro names that should be treated as `Apply!`.
/// * `ignored_traits`: A list of traits to ignore in the signature constraints.
///
/// Example:
/// ```toml
/// [package.metadata.document_signature]
/// brand_mappings = { "OptionBrand" = "Option", "VecBrand" = "Vec" }
/// apply_macro_aliases = ["MyApply"]
/// ignored_traits = ["Clone", "Debug"]
/// ```
/// Generates documentation for type parameters.
///
/// This macro analyzes the item's signature (function, struct, enum, impl block, etc.)
/// and generates a documentation comment list based on the provided descriptions.
///
/// When used within a module annotated with [`#[document_module]`](macro@document_module),
/// it benefits from automatic `Self` resolution and is applied as part of the module-level
/// documentation pass.
///
/// ### Syntax
///
/// ```ignore
/// #[document_type_parameters(
/// "Description for first parameter",
/// ("OverriddenName", "Description for second parameter"),
/// ...
/// )]
/// pub fn function_name<Generics>(params) -> ReturnType { ... }
/// ```
///
/// It can also be used on other items like `impl` blocks:
///
/// ```ignore
/// #[document_type_parameters("Description for T")]
/// impl<T> MyType<T> { ... }
/// ```
///
/// * `Descriptions`: A comma-separated list. Each entry can be either a string literal
/// or a tuple of two string literals `(Name, Description)`.
///
/// ### Generates
///
/// A list of documentation comments, one for each generic parameter, prepended to the
/// function definition.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[document_type_parameters(
/// "The type of the elements.",
/// ("E", "The error type.")
/// )]
/// pub fn map<T, ERR>(...) { ... }
///
/// // Expanded code
/// /// ### Type Parameters
/// /// * `T`: The type of the elements.
/// /// * `E`: The error type.
/// pub fn map<T, ERR>(...) { ... }
/// ```
///
/// ### Constraints
///
/// * The number of arguments must exactly match the number of generic parameters
/// (including lifetimes, types, and const generics) in the function signature.
/// Generates documentation for a function's parameters.
///
/// This macro analyzes the function signature and generates a documentation comment
/// list based on the provided descriptions. It also handles curried return types.
///
/// It can also be used on `impl` blocks to provide a common description for the receiver (`self`)
/// parameter of methods within the block.
///
/// ### Syntax
///
/// For functions:
/// ```ignore
/// #[document_parameters(
/// "Description for first parameter",
/// ("overridden_name", "Description for second parameter"),
/// ...
/// )]
/// pub fn function_name(params) -> impl Fn(...) { ... }
/// ```
///
/// For `impl` blocks:
/// ```ignore
/// #[document_parameters("Description for receiver")]
/// impl MyType {
/// #[document_parameters]
/// pub fn method_with_receiver(&self) { ... }
///
/// #[document_parameters("Description for arg")]
/// pub fn method_with_args(&self, arg: i32) { ... }
/// }
/// ```
///
/// * `Descriptions`: A comma-separated list. Each entry can be either a string literal
/// or a tuple of two string literals `(Name, Description)`.
/// * For `impl` blocks: Exactly one string literal describing the receiver parameter.
///
/// ### Generates
///
/// A list of documentation comments, one for each parameter, prepended to the
/// function definition.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[document_parameters(
/// "The first input value.",
/// ("y", "The second input value.")
/// )]
/// pub fn foo(x: i32) -> impl Fn(i32) -> i32 { ... }
///
/// // Expanded code
/// /// ### Parameters
/// /// * `x`: The first input value.
/// /// * `y`: The second input value.
/// pub fn foo(x: i32) -> impl Fn(i32) -> i32 { ... }
/// ```
///
/// ```ignore
/// // Invocation on impl block
/// #[document_parameters("The list instance")]
/// impl<A> MyList<A> {
/// #[document_parameters("The element to push")]
/// pub fn push(&mut self, item: A) { ... }
/// }
///
/// // Expanded code
/// impl<A> MyList<A> {
/// /// ### Parameters
/// /// * `&mut self`: The list instance
/// /// * `item`: The element to push
/// pub fn push(&mut self, item: A) { ... }
/// }
/// ```
///
/// ### Constraints
///
/// * The number of arguments must exactly match the number of function parameters
/// (excluding `self` but including parameters from curried return types).
///
/// ### Configuration
///
/// This macro can be configured via `Cargo.toml` under `[package.metadata.document_signature]`.
///
/// * `apply_macro_aliases`: A list of macro names that should be treated as `Apply!` for curried parameter extraction.
///
/// Example:
/// ```toml
/// [package.metadata.document_signature]
/// apply_macro_aliases = ["MyApply"]
/// ```
/// Generates documentation for the return value of a function.
///
/// This macro adds a "Returns" section to the function's documentation.
///
/// ### Syntax
///
/// ```ignore
/// #[document_returns("Description of the return value.")]
/// pub fn foo() -> i32 { ... }
/// ```
///
/// ### Generates
///
/// A documentation comment describing the return value.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[document_returns("The sum of x and y.")]
/// pub fn add(x: i32, y: i32) -> i32 { ... }
///
/// // Expanded code
/// /// ### Returns
/// /// The sum of x and y.
/// pub fn add(x: i32, y: i32) -> i32 { ... }
/// ```
/// Inserts a `### Examples` heading and validates doc comment code blocks.
///
/// This attribute macro expands in-place to a `### Examples` heading. Example
/// code is written as regular doc comments using fenced code blocks after the
/// attribute. Every Rust code block must contain at least one assertion macro
/// invocation (e.g., `assert_eq!`, `assert!`).
///
/// ### Syntax
///
/// ```ignore
/// #[document_examples]
/// ///
/// /// ```
/// /// let result = add(1, 2);
/// /// assert_eq!(result, 3);
/// /// ```
/// pub fn add(x: i32, y: i32) -> i32 { ... }
/// ```
///
/// ### Generates
///
/// A `### Examples` heading is inserted at the attribute's position. The code
/// blocks in the doc comments are validated but not modified.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[document_examples]
/// ///
/// /// ```
/// /// let x = my_fn(1, 2);
/// /// assert_eq!(x, 3);
/// /// ```
/// pub fn my_fn(a: i32, b: i32) -> i32 { a + b }
///
/// // Expanded code
/// /// ### Examples
/// ///
/// /// ```
/// /// let x = my_fn(1, 2);
/// /// assert_eq!(x, 3);
/// /// ```
/// pub fn my_fn(a: i32, b: i32) -> i32 { a + b }
/// ```
///
/// ### Errors
///
/// * Arguments are provided to the attribute.
/// * No Rust code block is found in the doc comments.
/// * A Rust code block does not contain an assertion macro invocation.
/// * The attribute is applied more than once to the same function.
/// Orchestrates documentation generation for an entire module.
///
/// This macro provides a centralized way to handle documentation for Higher-Kinded Type (HKT)
/// implementations. It performs a two-pass analysis of the module:
///
/// 1. **Context Extraction**: It scans for `impl_kind!` invocations and standard `impl` blocks
/// to build a comprehensive mapping of associated types (a "projection map").
/// 2. **Documentation Generation**: It processes all methods annotated with [`#[document_signature]`](macro@document_signature)
/// or [`#[document_type_parameters]`](macro@document_type_parameters), resolving `Self` and associated types
/// using the collected context.
/// 3. **Validation** (Optional): Checks that impl blocks and methods have appropriate documentation
/// attributes and emits compile-time warnings for missing documentation.
///
/// ### Syntax
///
/// Due to inner macro attributes being unstable, use the following wrapper pattern:
///
/// ```ignore
/// #[fp_macros::document_module]
/// mod inner {
/// // ... module content ...
/// }
/// pub use inner::*;
/// ```
///
/// To disable validation warnings:
///
/// ```ignore
/// #[fp_macros::document_module(no_validation)]
/// mod inner {
/// // ... module content ...
/// }
/// pub use inner::*;
/// ```
///
/// ### Generates
///
/// In-place replacement of [`#[document_signature]`](macro@document_signature) and
/// [`#[document_type_parameters]`](macro@document_type_parameters) attributes with generated documentation
/// comments. It also resolves `Self` and `Self::AssocType` references to their concrete
/// types based on the module's projection map.
///
/// ### Attributes
///
/// The macro supports several documentation-specific attributes for configuration:
///
/// * `#[document_default]`: (Used inside `impl` or `impl_kind!`) Marks an associated type as the
/// default to use when resolving bare `Self` references.
/// * `#[document_use = "AssocName"]`: (Used on `impl` or `fn`) Explicitly specifies which
/// associated type definition to use for resolution within that scope.
///
/// ### Validation
///
/// By default, `document_module` validates that impl blocks and methods have appropriate
/// documentation attributes and emits compile-time warnings for missing documentation.
///
/// To disable validation, use `#[document_module(no_validation)]`.
///
/// #### Validation Rules
///
/// An impl block or trait definition should have:
/// * `#[document_type_parameters]` if it has type parameters
/// * `#[document_parameters]` if it contains methods with receiver parameters (self, &self, &mut self)
///
/// A method should have:
/// * `#[document_signature]` - always recommended for documenting the Hindley-Milner signature
/// * `#[document_type_parameters]` if it has type parameters
/// * `#[document_parameters]` if it has non-receiver parameters
/// * `#[document_returns]` if it has a return type
/// * `#[document_examples]` - always recommended
///
/// A free function should have:
/// * `#[document_examples]` - always recommended
///
/// Documentation attributes must not be duplicated and must appear in canonical order:
/// `#[document_signature]` -> `#[document_type_parameters]` -> `#[document_parameters]` ->
/// `#[document_returns]` -> `#[document_examples]`.
///
/// Additionally, a lint warns when a named generic type parameter could be replaced with
/// `impl Trait` (i.e., it has trait bounds, appears in exactly one parameter position, does
/// not appear in the return type, and is not cross-referenced by other type parameters).
/// This lint skips trait implementations. Suppress it on individual functions or methods
/// with `#[allow_named_generics]`.
///
/// #### Examples of Validation
///
/// ```ignore
/// // This will emit warnings:
/// #[fp_macros::document_module]
/// mod inner {
/// pub struct MyType;
///
/// // WARNING: Impl block contains methods with receiver parameters
/// // but no #[document_parameters] attribute
/// impl MyType {
/// // WARNING: Method should have #[document_signature] attribute
/// // WARNING: Method has parameters but no #[document_parameters] attribute
/// // WARNING: Method has a return type but no #[document_returns] attribute
/// // WARNING: Method should have a #[document_examples] attribute
/// pub fn process(&self, x: i32) -> i32 { x }
/// }
/// }
/// ```
///
/// ```ignore
/// // Properly documented (no warnings):
/// #[fp_macros::document_module]
/// mod inner {
/// pub struct MyType;
///
/// #[document_parameters("The MyType instance")]
/// impl MyType {
/// #[document_signature]
/// #[document_parameters("The input value")]
/// #[document_returns("The input value unchanged.")]
/// #[document_examples]
/// ///
/// /// ```
/// /// # use my_crate::MyType;
/// /// let t = MyType;
/// /// assert_eq!(t.process(42), 42);
/// /// ```
/// pub fn process(&self, x: i32) -> i32 { x }
/// }
/// }
/// ```
///
/// ```ignore
/// // Disable validation to suppress warnings:
/// #[fp_macros::document_module(no_validation)]
/// mod inner {
/// // ... undocumented code won't produce warnings ...
/// }
/// ```
///
/// ### Hierarchical Configuration
///
/// When resolving the concrete type of `Self`, the macro follows this precedence:
///
/// 1. **Method Override**: `#[document_use = "AssocName"]` on the method.
/// 2. **Impl Block Override**: `#[document_use = "AssocName"]` on the `impl` block.
/// 3. **(Type, Trait)-Scoped Default**: `#[document_default]` on the associated type definition
/// in a trait `impl` block.
/// 4. **Module Default**: `#[document_default]` on the associated type definition in `impl_kind!`.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #[fp_macros::document_module]
/// mod inner {
/// use super::*;
///
/// impl_kind! {
/// for MyBrand {
/// #[document_default]
/// type Of<'a, T: 'a>: 'a = MyType<T>;
/// }
/// }
///
/// impl Functor for MyBrand {
/// #[document_signature]
/// fn map<'a, A: 'a, B: 'a, Func>(
/// f: Func,
/// fa: Apply!(<Self as Kind!(type Of<'a, T: 'a>: 'a;)>::Of<'a, A>),
/// ) -> Apply!(<Self as Kind!(type Of<'a, T: 'a>: 'a;)>::Of<'a, B>)
/// where
/// Func: Fn(A) -> B + 'a
/// {
/// todo!()
/// }
/// }
/// }
/// pub use inner::*;
///
/// // Expanded code
/// mod inner {
/// use super::*;
///
/// // ... generated Kind implementations ...
///
/// impl Functor for MyBrand {
/// /// ### Type Signature
/// /// `forall a b. (a -> b, MyType a) -> MyType b`
/// fn map<'a, A: 'a, B: 'a, Func>(
/// f: Func,
/// fa: Apply!(<Self as Kind!(type Of<'a, T: 'a>: 'a;)>::Of<'a, A>),
/// ) -> Apply!(<Self as Kind!(type Of<'a, T: 'a>: 'a;)>::Of<'a, B>)
/// where
/// Func: Fn(A) -> B + 'a
/// {
/// todo!()
/// }
/// }
/// }
/// pub use inner::*;
/// ```
/// Monadic do-notation.
///
/// Desugars flat monadic syntax into nested `bind` calls, matching
/// Haskell/PureScript `do` notation. Supports both explicit-brand and
/// inferred-brand modes.
///
/// ### Syntax
///
/// ```ignore
/// // Explicit mode: brand specified, pure() rewritten automatically
/// m_do!(Brand {
/// x <- expr; // Bind: extract value from monadic computation
/// y: Type <- expr; // Typed bind: with explicit type annotation
/// _ <- expr; // Discard bind: sequence, discarding the result
/// expr; // Sequence: discard result (shorthand for `_ <- expr;`)
/// let z = expr; // Let binding: pure, not monadic
/// let w: Type = expr; // Typed let binding
/// pure(z) // pure() rewritten to pure::<Brand, _>(z)
/// })
///
/// // Inferred mode: brand inferred from container types
/// m_do!({
/// x <- Some(5); // Brand inferred from Some(5) via InferableBrand
/// y <- Some(x + 1);
/// Some(x + y) // Write concrete constructor (pure() not available)
/// })
///
/// // By-reference modes:
/// m_do!(ref Brand { ... }) // Explicit, ref dispatch
/// m_do!(ref { ... }) // Inferred, ref dispatch
/// ```
///
/// * `Brand` (optional): The monad brand type. When omitted, the brand is inferred
/// from container types via `InferableBrand`.
/// * `ref` (optional): Enables by-reference dispatch. Closures receive `&A`
/// instead of `A`, routing through `RefSemimonad::ref_bind`. Typed binds
/// use the type as-is (include `&` in the type annotation). Untyped binds
/// get `: &_` added automatically.
/// * In explicit mode, bare `pure(args)` calls are rewritten to `pure::<Brand, _>(args)`
/// (or `ref_pure::<Brand, _>(&args)` in ref mode).
/// * In inferred mode, bare `pure(args)` calls emit a `compile_error!` because
/// `pure` has no container argument to infer the brand from. Write concrete
/// constructors instead (e.g., `Some(x)` instead of `pure(x)`).
///
/// ### Statement Forms
///
/// | Syntax | Explicit expansion | Inferred expansion |
/// |--------|--------------------|--------------------|
/// | `x <- expr;` | `explicit::bind::<Brand, _, _, _, _>(expr, move \|x\| { ... })` | `bind(expr, move \|x\| { ... })` |
/// | `x: Type <- expr;` | Same with `\|x: Type\|` | Same with `\|x: Type\|` |
/// | `expr;` | `explicit::bind::<Brand, _, _, _, _>(expr, move \|_\| { ... })` | `bind(expr, move \|_\| { ... })` |
/// | `let x = expr;` | `{ let x = expr; ... }` | `{ let x = expr; ... }` |
/// | `expr` (final) | Emitted as-is | Emitted as-is |
///
/// ### Examples
///
/// ```ignore
/// // Inferred mode (primary API for single-brand types)
/// let result = m_do!({
/// x <- Some(5);
/// y <- Some(x + 1);
/// let z = x * y;
/// Some(z)
/// });
/// assert_eq!(result, Some(30));
///
/// // Expands to:
/// let result = bind(Some(5), move |x| {
/// bind(Some(x + 1), move |y| {
/// let z = x * y;
/// Some(z)
/// })
/// });
/// ```
///
/// ```ignore
/// // Explicit mode (for ambiguous types or to use pure())
/// let result = m_do!(VecBrand {
/// x <- vec![1, 2];
/// y <- vec![10, 20];
/// pure(x + y)
/// });
/// assert_eq!(result, vec![11, 21, 12, 22]);
///
/// // Expands to:
/// let result = explicit::bind::<VecBrand, _, _, _, _>(vec![1, 2], move |x| {
/// explicit::bind::<VecBrand, _, _, _, _>(vec![10, 20], move |y| {
/// pure::<VecBrand, _>(x + y)
/// })
/// });
/// ```
///
/// ### Ref mode: multi-bind limitation
///
/// In ref mode, each bind generates a `move` closure that receives `&A`.
/// Inner closures cannot capture references from outer binds because the
/// reference lifetime is scoped to the outer closure. Attempting to use a
/// ref-bound variable in a later bind produces a lifetime error.
///
/// **Workaround:** use `let` bindings to dereference or clone values so
/// they become owned and can be captured by later closures:
///
/// ```ignore
/// m_do!(ref LazyBrand {
/// x: &i32 <- lazy_a;
/// let x_val = *x; // dereference into owned value
/// y: &i32 <- lazy_b;
/// pure(x_val + *y) // x_val is owned, safe to use here
/// })
/// ```
///
/// When all binds are independent (no bind uses the result of another),
/// prefer [`a_do!`] instead. Applicative do-notation evaluates all
/// expressions independently, so there is no closure nesting and no
/// capture issue.
/// Applicative do-notation.
///
/// Desugars flat applicative syntax into `pure` / `map` / `lift2`-`lift5`
/// calls, matching PureScript `ado` notation. Unlike [`m_do!`], bindings are
/// independent: later bind expressions cannot reference earlier bound variables.
/// Supports both explicit-brand and inferred-brand modes.
///
/// ### Syntax
///
/// ```ignore
/// // Explicit mode
/// a_do!(Brand {
/// x <- expr; // Bind: independent applicative computation
/// y: Type <- expr; // Typed bind: with explicit type annotation
/// _ <- expr; // Discard bind: compute for effect
/// expr; // Sequence: shorthand for `_ <- expr;`
/// let z = expr; // Let binding: placed inside the combining closure
/// expr // Final expression: the combining body
/// })
///
/// // Inferred mode (brand inferred from container types)
/// a_do!({
/// x <- Some(3);
/// y <- Some(4);
/// x + y
/// })
///
/// // By-reference modes:
/// a_do!(ref Brand { ... }) // Explicit, ref dispatch
/// a_do!(ref { ... }) // Inferred, ref dispatch
/// ```
///
/// * `Brand` (optional): The applicative brand type. When omitted, the brand is
/// inferred from container types via `InferableBrand`.
/// * `ref` (optional): Enables by-reference dispatch. The combining closure
/// receives references (`&A`, `&B`, etc.) via `RefLift::ref_lift2`. Typed
/// binds use the type as-is (include `&`). Untyped binds get `: &_`.
/// * Bind expressions are evaluated independently (applicative, not monadic).
/// * `let` bindings before any `<-` are hoisted outside the combinator call.
/// * `let` bindings after a `<-` are placed inside the combining closure.
/// * In explicit mode, bare `pure(args)` calls are rewritten to `pure::<Brand, _>(args)`.
/// * In inferred mode, bare `pure(args)` calls emit a `compile_error!`.
/// * In inferred mode with 0 binds, a `compile_error!` is emitted because
/// `pure()` requires a brand. Write the concrete constructor directly.
///
/// ### Desugaring
///
/// | Binds | Explicit expansion | Inferred expansion |
/// |-------|--------------------|--------------------|
/// | 0 | `pure::<Brand, _>(final_expr)` | `compile_error!` |
/// | 1 | `explicit::map::<Brand, _, _, _, _>(\|x\| body, expr)` | `map(\|x\| body, expr)` |
/// | N (2-5) | `explicit::liftN::<Brand, ...>(\|x, y, ...\| body, ...)` | `liftN(\|x, y, ...\| body, ...)` |
///
/// ### Examples
///
/// ```ignore
/// use fp_library::functions::*;
/// use fp_macros::a_do;
///
/// // Inferred mode: two independent computations combined with lift2
/// let result = a_do!({
/// x <- Some(3);
/// y <- Some(4);
/// x + y
/// });
/// assert_eq!(result, Some(7));
///
/// // Expands to:
/// let result = lift2(|x, y| x + y, Some(3), Some(4));
///
/// // Inferred mode: single bind uses map
/// let result = a_do!({ x <- Some(5); x * 2 });
/// assert_eq!(result, Some(10));
///
/// // Expands to:
/// let result = map(|x| x * 2, Some(5));
/// ```
///
/// ```ignore
/// // Explicit mode: zero-bind block uses pure (requires brand)
/// let result: Option<i32> = a_do!(OptionBrand { 42 });
/// assert_eq!(result, Some(42));
///
/// // Expands to:
/// let result: Option<i32> = pure::<OptionBrand, _>(42);
///
/// // Explicit mode: single bind
/// let result = a_do!(OptionBrand { x <- Some(5); x * 2 });
///
/// // Expands to:
/// let result = explicit::map::<OptionBrand, _, _, _, _>(|x| x * 2, Some(5));
/// ```
/// Includes a markdown file with relative `.md` links rewritten to rustdoc intra-doc links.
///
/// This macro reads a markdown file at compile time (relative to `CARGO_MANIFEST_DIR`)
/// and rewrites same-directory `.md` links to point at `crate::docs::module_name`
/// submodules, making cross-document links work in rendered rustdoc output.
///
/// ### Syntax
///
/// ```ignore
/// #![doc = include_documentation!("docs/hkt.md")]
/// ```
///
/// * `path`: A string literal path to a markdown file, relative to `CARGO_MANIFEST_DIR`.
///
/// ### Generates
///
/// A string literal containing the file contents with rewritten links.
/// Same-directory `.md` links are converted to rustdoc intra-doc link references;
/// all other links are left unchanged.
///
/// ### Examples
///
/// ```ignore
/// // Invocation
/// #![doc = include_documentation!("docs/hkt.md")]
///
/// // Link rewriting:
/// // [text](./foo-bar.md) -> [text][crate::docs::foo_bar]
/// // [text](foo-bar.md) -> [text][crate::docs::foo_bar]
/// // [text](../other.md) -> unchanged (contains path separator)
/// // [text](https://...) -> unchanged (not .md)
/// ```