tisel 0.1.1

Effective type-based pseudodynamic dispatch to impls, enums and typeid
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
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
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
//! Macros for implementing the [`crate::typematch`] macro. Actual typematch macro is in the crate
//! root.
//!
//! These macros are not part of any public interface. Do not rely on them externally.
//!
//! Many of these macros are designed to take input exclusively from other macros (either this
//! module or the main macro). They often will not document their input structure - that is usually
//! dictated by whatever macro calls them.
//!
//! Something important to note is that we cannot use repeated macro calls until we are generating
//! the match statement. This is because macros simply can't generate macro arms individually, so
//! the number of macro arms must be directly "repeat-generatable" from the input of whatever macro
//! stage actually makes them. Hence, pre-macro-arm-generation must correctly generate enough
//! information to get the number of macro arms to be generated (even if some of them can be made
//! unreachable later).
//!
//! See [`crate::_macro`] for how these are named.

/// Macro to simplify and modularise the parsing of "single-mode" match and separate out all
/// the commonalities, to dispatch into [__typematch_parse_typeid_generators].
///
/// This is to keep things nice and modular and avoid awful copy-paste nonsense
///
/// Called by: [crate::typematch]
/// Calls: [__typematch_parse_typeid_generators]
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_single_mode_dispatch {
    ({
        // Expression for the single typeid generator to provide to the main typeid generator macro
        // This should be a :tt-bundle (in `[]`)
        single_typeid_gen: $single_typeid_gen:tt,
        // The actual block containing match arms. You can capture as a simple :tt and this
        // will do all the parsing for single-mode match arms, and perform any weirdness needed to
        // ensure the __typematch_parse_typeid_generators works ok.
        match_block: {
            $($(|)? $(@_)? $(type $type_alias:ident = $(@_)?)? $($($match_types:ty)|+)? $(as $witness:ident)?
                => $output_expr:expr
            ),*$(,)?
        }
    }) => {
        // All "|-patterns" for single matchers are "inner" |-patterns and need not be unwound
        // here.
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: $single_typeid_gen,
            parsed_typeid_gens: [],
            partially_parsed_match_arm_specs: [$({
                // We insert `@_` in here - it's fine when it's "always there" as it just gets
                // ignored (the actual "unconditional match" is determined by the presence or
                // absence of type alternates). It's presence, however, prevents a syntax ambiguity
                // error by preventing an empty single match pattern. This ambiguity error is also
                // not easy to figure out the real source of either.
                unparsed_typeid_patterns: [@_ $(type $type_alias = )? $($($match_types)|+)? $(as $witness)?],
                output_expr: {$output_expr}
            })* /* each arm */]
        }}
    };
}

/// This is a slightly-but-not-mostly tt-munching parser that constructs information about the
/// TypeId generator expressions. It can't avoid the need to munch because of parsing ambiguities.
///
/// This is the "entrypoint" part - it parses the typeid generator specifiers (using a bit of
/// tt-munching but hopefully not too much), and then going further down.
///
/// important performance notes - put stuff that does actual matching near the front, and
/// other "bundled" information near the back.
///
/// Calls: [__typematch_top_level_arms_syntax_split]
/// Called by: [crate::typematch] and []
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_parse_typeid_generators {
    // Anyref specifiers
    //
    // Comma is needed for disambiguation - that's why it's included with the unparsed `tt`s and
    // not on it's own.
    ({
        unparsed_typeid_gens: [anyref ($anyid:ident = $anyref_expr:expr) $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: anyref { $anyid },
                expr: $crate::_reexports::core::any::Any::type_id($anyid),
                pre_expr_name: $anyid,
                pre_expr_ty_constraint: [&dyn $crate::_reexports::core::any::Any],
                pre_expr: $anyref_expr
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    ({
        unparsed_typeid_gens: [anyref $anyid:ident $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: anyref { $anyid },
                expr: $crate::_reexports::core::any::Any::type_id($anyid),
                pre_expr_name: $anyid,
                pre_expr_ty_constraint: [&dyn $crate::_reexports::core::any::Any],
                pre_expr: { $anyid }
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    // Anymut specifiers
    //
    // Comma is needed for disambiguation - that's why it's included with the unparsed `tt`s and
    // not on it's own.
    ({
        unparsed_typeid_gens: [anymut ($anyid:ident = $anymut_expr:expr) $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: anymut { $anyid },
                expr: $crate::_reexports::core::any::Any::type_id(&*$anyid),
                pre_expr_name: $anyid,
                pre_expr_ty_constraint: [&mut dyn $crate::_reexports::core::any::Any],
                pre_expr: $anymut_expr
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    ({
        unparsed_typeid_gens: [anymut $anyid:ident $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: anymut { $anyid },
                expr: $crate::_reexports::core::any::Any::type_id(&*$anyid),
                pre_expr_name: $anyid,
                pre_expr_ty_constraint: [&mut dyn $crate::_reexports::core::any::Any],
                pre_expr: { $anyid }
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    // value specifiers
    //
    // This handles the cases with and without type ascriptions.
    ({
        unparsed_typeid_gens: [val ($val_id:ident = $val_expr:expr) $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: val { val_id: $val_id },
                expr: $crate::_reexports::core::any::Any::type_id(&$val_id),
                pre_expr_name: $val_id,
                pre_expr_ty_constraint: [_],
                pre_expr: $val_expr
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    ({
        unparsed_typeid_gens: [val ($val_id:ident: $val_ty:ty = $val_expr:expr) $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: val { val_id: $val_id, ty: $val_ty },
                expr: $crate::_reexports::core::any::TypeId::of::<$val_ty>(),
                pre_expr_name: $val_id,
                pre_expr_ty_constraint: [$val_ty],
                pre_expr: $val_expr
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    ({
        unparsed_typeid_gens: [val $val_id:ident $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: val { val_id: $val_id },
                expr: $crate::_reexports::core::any::Any::type_id(&$val_id),
                pre_expr_name: $val_id,
                pre_expr_ty_constraint: [_],
                pre_expr: { $val_id }
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    ({
        unparsed_typeid_gens: [val $val_id:ident: $val_ty:ty $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators!{{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: val { val_id: $val_id, ty: $val_ty },
                expr: $crate::_reexports::core::any::TypeId::of::<$val_ty>,
                pre_expr_name: $val_id,
                pre_expr_ty_constraint: [$val_ty],
                pre_expr: { $val_id }
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    // Inverse type specifiers
    ({
        unparsed_typeid_gens: [out $type_to_match:ty $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators! {{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: out_ty { $type_to_match },
                expr: $crate::_reexports::core::any::TypeId::of::<$type_to_match>(),
                pre_expr_name: __type_preexpr,
                pre_expr_ty_constraint: [()],
                pre_expr: ()
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    // Type specifiers
    ({
        unparsed_typeid_gens: [type $type_to_match:ty $(, $($unparsed_typeid_gens:tt)*)?],
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators! {{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                matchmode: ty { $type_to_match },
                expr: $crate::_reexports::core::any::TypeId::of::<$type_to_match>(),
                pre_expr_name: __type_preexpr,
                pre_expr_ty_constraint: [()],
                pre_expr: ()
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    ({
        unparsed_typeid_gens: [$type_to_match:ty $(, $($unparsed_typeid_gens:tt)*)?],
        // parsed structured info on the typeid-generating expressions
        // includes the actual expressions to be included in the "matched-on" array, as well as
        // information on the type of typeid generator it was for use by the match arms later.
        //
        // In this part, we just have the existing ones as `tt`s.
        parsed_typeid_gens: [$($parsed_typeid_gens:tt)*],
        // unparsed match arm specifiers. Not processed here - we treat it as an opaque `tt`
        // bundle. (held in `{}`, we don't even bother examining this until the initial typeid
        // parsing is done).
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_parse_typeid_generators! {{
            unparsed_typeid_gens: [$($($unparsed_typeid_gens)*)?],
            // Note that we put the new one at the *end* - we're munching through the unparsed ones
            // from start to finish, so we need the output on the end to ensure that the order is
            // maintained.
            parsed_typeid_gens: [$($parsed_typeid_gens)* {
                // "mode" of the matcher - contains the actual mode as well as associated data for
                // it (in this case the type itself)
                matchmode: ty { $type_to_match },
                // expression to get the actual typeid - used in the "top level" expression that
                // gets matched.
                expr: $crate::_reexports::core::any::TypeId::of::<$type_to_match>(),
                // Name to store the "pre-expression"
                //
                // For types there is no pre-expression, but we can't just use `_` as it's not an
                // identifier. Hence, we use __type_preexpr. Hygiene should prevent issues anyway.
                pre_expr_name: __type_preexpr,
                // Type constraint on the pre-expression, to ease deduction
                //
                // In this case it's just nothing since type based typeid generators have no
                // preexpr
                pre_expr_ty_constraint: [()],
                // Value of the "pre-expression"
                pre_expr: ()
            }],
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs
        }}
    };
    // Terminator - when there are no more things left to grab...
    ({
        unparsed_typeid_gens: [$(,)?],
        parsed_typeid_gens: [$({
            matchmode: $matchmode:ident $matchmode_data:tt,
            expr: $typeid_expr:expr,
            pre_expr_name: $pre_expr_name:ident,
            pre_expr_ty_constraint: [$($pre_expr_ty_constraint:tt)*],
            pre_expr: $pre_expr:expr
        })*],
        // to be parsed later!
        partially_parsed_match_arm_specs: $unparsed_match_arm_specs:tt
    }) => {
        $crate::__typematch_top_level_arms_syntax_split!{{
            partially_parsed_match_arm_specs: $unparsed_match_arm_specs,
            pre_match_statements: [
                $(let $pre_expr_name: $($pre_expr_ty_constraint)* = $pre_expr;)*
            ],
            matched_expression: [
                ($($typeid_expr,)*)
            ],
            // Reduced-form typeid_generator_info
            typeid_generator_info: [$({
                matchmode: $matchmode $matchmode_data,
                expr: $typeid_expr
            })*]
        }}
    };
    // Nice error if we encounter unparseable stuff
    ({
        unparsed_typeid_gens: [$($unparseable_typeid_gens:tt)*],
        $($_tail:tt)*
    }) => {
        $crate::_reexports::core::compile_error!(
            $crate::_reexports::core::concat!(
                "Unparseable typeid generator expressions found: ",
                $crate::_reexports::core::stringify!(($($unparseable_typeid_gens)*)),
                "\n",
                "* `anyref <ident>` - simple anyref type-id-gen-expr\n",
                "* `anyref (<ident> = <some expression producing &dyn Any or &impl Any>)` - anyref type-id-gen-expr with custom value\n",
                "* `anymut <ident>` - simple anymut type-id-gen-expr\n",
                "* `anymut (<ident> = <some expression producing &mut dyn Any or &impl Any>)` - anymut type-id-gen-expr with custom value\n",
                "* `val <ident> [: <type>]?` - simply by-value type-id-gen-expr\n",
                "* `val (<ident> [: <type>]? = <some expression producing value>)` - by-value type-id-gen-expr with expression\n",
                "* `out <type>` - match on a given type, but provide the witness flipped for ease of use\n",
                "* `type <type>` - match on a given type\n",
                "* `<type>` - match on a given type\n",
            )
        )
    };
}

/// Something very important to know is that we can in fact "replicate" repeated data inside
/// nested repeats, as long as there is no ambiguous iteration. The most important thing is to
/// avoid *constructing any `match` statements before we can unambiguously iterate over all
/// concrete match arms*, as you can't build match arms as macro output - given that we have
/// such a complex association between match arms and the corresponding expression, this makes
/// things harder.
///
/// At this point all top-level |-patterns have already been unwrapped.
///
/// To make this work, we need recursion but we cannot simply do a repetition over the output of
/// this macro, as we need a single invokation to create a match statement from. Only at the
/// last possible stage can we actually use repeated invokations of the macro.
///
/// Many operations here require using macro rule matching to select a path. This is highly
/// undesirable for anything but the bottommost level, as it would require a highly inefficient
/// pushdown parser to accumulate output (which would require extremely high amounts of
/// recursion, as you'd need to go through a combinatoric amount of recursion).
///
/// To deal with the actual process of analysis, the arms are stored in a sort of
/// "progressive-branching" tree, and this stage of the process primarily involves
/// *syntactically* removing each matcher specification from the remaining specifications
/// (including things which might not end up being valid), and storing information about those
/// for later analysis. Importantly, this is done in bulk/parallel (with repeats).
///
/// The branching aspect of this happens in a bit. This submacro just extracts the syntax data
/// into a coherent sequence of tt-bundles
///
/// This also passes the output into a macro that verifies there is at least one exhaustive
/// branch - if there isn't, then a compile_error! is generated.
///
/// Calls: [__typematch_top_level_arms_branch_dispatch] - this provides the output to the actual
///   branch splayer as well as the macro that verifies exhaustivity.
/// Called by: [crate::__typematch_parse_typeid_generators]
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_top_level_arms_syntax_split {
    ({
        partially_parsed_match_arm_specs: [$({
            // Important note here - `_` is a pattern and will not be classified as an identifier.
            //
            // We cannot, however, extract it as a real variable because of follow-set issues,
            // which means we can't provide users with checking
            unparsed_typeid_patterns: [$($(@_)? $(type $type_alias:ident = $(@_)?)? $($($match_types:ty)|+)? $(as $witness:ident)?),*],
            output_expr: $output_expr_bundle:tt
        })*],
        // pre-match statements as a `tt`-bundle inside []
        pre_match_statements: $pre_match_statements:tt,
        // the actual matched expression as a `tt`-bundle inside `[]`
        matched_expression: $matched_expression_bundle:tt,
        // the typeid generator infos (in reduced form without the pre-expr stuff)
        typeid_generator_info: $typeid_generator_info:tt
    }) => {
        $crate::__typematch_top_level_arms_branch_dispatch!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: [],
                leaf: {
                    remaining_typeid_patterns: [$({
                        // no type branches means that this is an unconditional acceptance mode thing.
                        // To make this work, we cannot do macro-based matching while branching (as we
                        // need a single macro call to make the final match statement). Instead, to
                        // make this work, we always do an "always-accept" branch, BUT we conditionally
                        // include an inner `[]` inside the `tt`. Then, in the final output, we create
                        // a match statement branch that will never match.
                        //
                        // Important to note here is that the deletion
                        type_branches: [
                            // unconditional-acceptance type match branch, with the marker for
                            // elimination in branching.
                            //
                            // The match_types tt goes at the back to enable better macro pattern
                            // matching semantics.
                            [[u] $([$($match_types)+])?]
                            $($([[t: $match_types]])+)?
                        ],
                        // TT-bundle everything unconditionally, for later parsing.
                        type_alias: [$($type_alias)?],
                        witness_or_ignore: [$($witness)?]
                    })*],
                    output_expr: $output_expr_bundle
                }
            })*],
            pre_match_statements: $pre_match_statements,
            matched_expression: $matched_expression_bundle,
            typeid_generator_info: $typeid_generator_info
        }}
    };
}

/// Intermediary macro that takes the output from [__typematch_top_level_arms_syntax_split] and
/// puts it into two places:
/// * [__typematch_top_level_arms_branch_extract] to actually generate the match statement
///   (initially, by splaying out all the inner |-patterns)
/// * [__typematch_top_level_arms_branch_verify_exhaustive] to verify that the arms are exhaustive
///   (relatively efficiently)
///
/// It does these both "in parallel", so it doesn't add horrible recursion.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_top_level_arms_branch_dispatch {
    ($output:tt) => {{
        $crate::__typematch_top_level_arms_branch_verify_exhaustive!(@entry $output);
        $crate::__typematch_top_level_arms_branch_extract!($output)
    }};
}

/// Verify that there is at least one exhaustive pattern in all the parsed patterns.
///
/// This is done because we cannot simply use syntax constraints in the root macro due to
/// parsing-set ambiguity (plus doing it this way also avoids forcing orders on users).
///
/// This might seem like it would be horrible, due to the existence of internal |-patterns.
/// However, the syntax splitter always puts any unconstrained components of each internal
/// |-pattern at the front, and basically just marks it for later deletion if there are any types.
///
/// That means that, while we do need to tt-munch through each arm, all we need to do to see if an
/// arm is exhaustive is match on the first `[_]`-part of the |-pattern being undeleted. If at any
/// point we encounter a matcher that is exhaustive, we need not recurse any further.
///
/// We can also do multiple matchers at once by simply doing multiple fallback rules. The last rule
/// then strips off the ones we've checked so far (that is, ones we know aren't exhaustive), and
/// tries again with the remainder.
///
/// An empty list of rules is definitely *not* exhaustive, so that rule then produces a simple
/// `compile_error!();` statement
///
/// To make writing the rules easier, we also have an entrypoint that takes the complex input
/// format and just turns it into a list of lists-of-constraint-alternates.
///
/// Called by:
/// * [__typematch_top_level_arms_branch_dispatch]
///
/// Calls:
/// * [__typematch_top_level_arms_branch_verify_exhaustive_inner] - actual implementation.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_top_level_arms_branch_verify_exhaustive {
    (@entry {
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: [],
            leaf: {
                remaining_typeid_patterns: [$({
                    type_branches: $type_alternates:tt,
                    type_alias: $_type_alias:tt,
                    witness_or_ignore: $_witness_or_ignore:tt
                })*],
                output_expr: {$_output_expr:expr}
            }
        })*],
        $($_other:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_verify_exhaustive_inner!([$(
            [$({alternates: $type_alternates})*]
        )*])
    };
}

/// Actual implementation of [__typematch_top_level_arms_branch_verify_exhaustive] using a
/// much-simplified list form.
///
/// Calls out to [crate::__macros_compile_error] for the error.
///
/// This checks for any rows that have their "unconstrained" constraint undeleted for all
/// patterns in a given index. This is easy to check, as that constraint is always at the front,
/// and all we need to do is match on all the ones which are `[_]` rather than with a `[_ tt:tt]`
/// to indicate deletion.
///
/// To do this effectively, we also provide several fallback rules that allow a single invokation
/// to eat through several match arms, reducing the risk of over-recursion, even though this is a
/// tt-muncher. The last rule peels off all the |-branches that have been checked so far and found
/// not to be exhaustive as this rule is now triggered.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_top_level_arms_branch_verify_exhaustive_inner {
    // Empty case - this is definitely not exhaustive!
    ([]) => {
        $crate::__macros_compile_error!("typematch statement is not exhaustive");
    };
    // Simple case where the first arm is fine. Similar cases for a while after too.
    ([
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        $_b1:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        $_b1:tt
        $_b2:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        $_b1:tt
        $_b2:tt
        $_b3:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        $_b1:tt
        $_b2:tt
        $_b3:tt
        $_b4:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        $_b1:tt
        $_b2:tt
        $_b3:tt
        $_b4:tt
        $_b5:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    ([
        $_b0:tt
        $_b1:tt
        $_b2:tt
        $_b3:tt
        $_b4:tt
        $_b5:tt
        $_b6:tt
        [$({alternates: [[ [u] ] $($_ts:tt)*]})*]
        $($rest:tt)*
    ]) => {};
    // None of the other rules matched.
    //
    // Note that this does *not* mean that the # of matchers is >8, because a smaller # of branches
    // with no non-exhaustive rules would also fail to match. This is why we use `?` on everything
    // to peel things off
    ([
        $_b0:tt
        $($_b1:tt
        $($_b2:tt
        $($_b3:tt
        $($_b4:tt
        $($_b5:tt
        $($_b6:tt
        $($_b7:tt
        $($rest:tt)*)?)?)?)?)?)?)?
    ]) => {
        /*
        $crate::__macros_compile_error!("recursing into:\n");
        ::core::compile_error!(
        stringify!(
            [$_b0 $($_b1 $($_b2 $($_b3 $($_b4 $($_b5 $($_b6 $($_b7 $($rest)*)?)?)?)?)?)?)?]
        )
        );*/
        $crate::__typematch_top_level_arms_branch_verify_exhaustive_inner!([
            $($($($($($($($($rest)*)?)?)?)?)?)?)?
        ])
    };
}

/// This is a recursive part of [`crate::typematch`] that takes the arms plus the next type-branches for
/// each arm, and splays out an arm for each possible |-type that extends the original arm in
/// the process of branching.
///
/// This (1/3rd) macro used to be part of a big macro, but it got split up into 3 components:
/// * [__typematch_top_level_arms_branch_extract] - this one, which has all these docs
/// * [__typematch_top_level_arms_branch_splay] - splays out one index or more than
///   one with correct recursive configuration from the extract component
/// * [__typematch_top_level_arms_branch_append] - acts on the append instructions and
///   calls back to the extract entry point.
///
/// To do this, we need to be able to unambiguously "splay" the arm-prefix data over the type
/// branches even though it's a collection of data. To do *that*, we hold it as a single `tt`
/// inside `[]`. Not only this, but we need to do the exact same for the remaining typeid
/// patterns, which means we need to do a 3-stage extract-splay-append:
/// * `extract` - extracts the next TypeId pattern data along with the remaining ones, allowing
///   the next one to be handled specifically
/// * `splay` - performs the actual branching over all the type constraints on this level,
///   producing more arrays. Each one has a copy of the prefixes.
/// * `append` - append the new arm data - inside each array - to the main sequence of arm
///    data for that.
///
/// For reduced recursion, this macro also allows splay to jump directly into the next splay, as
/// long as that splay information has "recursive" splay information. To manage this, it needs
/// compatibility in several respects:
/// * `extract` needs to have specialisation to create next-typeid-patterns which recursively store
///    their own next ones in a `tt`-bundle.
/// * `splay` needs to construct "recursive" append-commands. It does this via building up an
///     "append-tree" of the form [<existing append tree ([] = end)>;<next_to_append>]
///    This is needed because simple linear appending will not cooperate with unambiguous
///    iteration-based splaying.
/// * `append` needs to have specialised handling for these trees. For smaller lengths, it can
///    directly match on them. For larger lengths, it needs to do something a bit special (note
///    however that it should not ever get any length larger than the number of groups `extract` can
///    grab).
///    This is because the outermost component of the append list is essentially the "last"
///    part of the list, and hence should be at the end, so the inner parts need to be extracted
///    first.
///    To do this, `append` allows providing another repeat-arg called `extra_data` which is a list
///    of things to append after the current glob of stuff. Deeper `append_list` chains are solved
///    by calling `append` with this argument along with the new parts added before it
///
/// This macro is designed to take the toplevel arms information that has been modified such that
/// each index has a list of the relevant type constraint branches, and expand that out into every
/// individual branch (then call out to the next macro in the chain of analysis and generation when
/// it's done).
///
/// Calls:
/// * Final (terminating): [__typematch_splay_typeid_generator_info]
/// * Subcomponent: [__typematch_top_level_arms_branch_splay]
///
/// Called by: [__typematch_top_level_arms_branch_dispatch]
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_top_level_arms_branch_extract {
    // Terminator branch of the extraction rule - occurs when there are no more indices to parse
    // through
    //
    // This is at the top to stop the macro from recursing infinitely in the case that there are no
    // branches :p
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            leaf: {
                remaining_typeid_patterns: [],
                output_expr: {$output_expr:expr}
            }
        })*],
        pre_match_statements: $pre_match_statements:tt,
        matched_expression: $matched_expression_bundle:tt,
        typeid_generator_info: $typeid_generator_info:tt
    }) => {
        $crate::__typematch_splay_typeid_generator_info!{{
            match_arm_infos: [$({
                arm_index_data: $arm_prefix_data,
                typeid_generator_info: $typeid_generator_info,
                output_expr: {$output_expr}
            })*],
            pre_match_statements: $pre_match_statements,
            matched_expression: $matched_expression_bundle
        }}
    };

    // Some more specialised extractor parts, for extracting multiple layers at once and reducing
    // recusion.
    //
    // We do 2 and 4, starting at the largest. These ones use `tail` to avoid repetition
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            leaf: {
                remaining_typeid_patterns: [
                    $next_typeid_pattern_0:tt
                    $next_typeid_pattern_1:tt
                    $next_typeid_pattern_2:tt
                    $next_typeid_pattern_3:tt
                    $($remaining_typeid_patterns:tt)*
                ],
                output_expr: {$output_expr:expr}
            }
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_splay!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: $arm_prefix_data,
                next_typeid_pattern: [
                    recurse $next_typeid_pattern_0 [
                        recurse $next_typeid_pattern_1 [
                            recurse $next_typeid_pattern_2 [
                                direct $next_typeid_pattern_3
                            ]
                        ]
                    ]
                ],
                append_tree: [],
                leaf: {
                    remaining_typeid_patterns: [$($remaining_typeid_patterns)*],
                    output_expr: {$output_expr}
                }
            })*],
            $($tail)*
        }}
    };

    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            leaf: {
                remaining_typeid_patterns: [
                    $next_typeid_pattern_0:tt
                    $next_typeid_pattern_1:tt
                    $($remaining_typeid_patterns:tt)*
                ],
                output_expr: {$output_expr:expr}
            }
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_splay!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: $arm_prefix_data,
                next_typeid_pattern: [
                    recurse $next_typeid_pattern_0 [
                        direct $next_typeid_pattern_1
                    ]
                ],
                append_tree: [],
                leaf: {
                    remaining_typeid_patterns: [$($remaining_typeid_patterns)*],
                    output_expr: {$output_expr}
                }
            })*],
            $($tail)*
        }}
    };

    // This stage extracts the next typeid pattern, allowing the leaf of unparsed information to be
    // treated as a block and allowing splaying
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            leaf: {
                remaining_typeid_patterns: [$next_typeid_pattern:tt $($remaining_typeid_patterns:tt)*],
                output_expr: {$output_expr:expr}
            }
        })*],
        pre_match_statements: $pre_match_statements:tt,
        matched_expression: $matched_expression_bundle:tt,
        typeid_generator_info: $typeid_generator_info:tt
    }) => {
        $crate::__typematch_top_level_arms_branch_splay!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: $arm_prefix_data,
                next_typeid_pattern: [direct $next_typeid_pattern],
                // This is parsed typeid patterns that haven't yet been appended to
                // the main prefix data, in the append_tree format
                //
                // This is what's used by the low-recursivity specialisations to build multiple
                append_tree: [],
                leaf: {
                    remaining_typeid_patterns: [$($remaining_typeid_patterns)*],
                    output_expr: {$output_expr}
                }
            })*],
            pre_match_statements: $pre_match_statements,
            matched_expression: $matched_expression_bundle,
            typeid_generator_info: $typeid_generator_info
        }}
    };

}

/// Subcomponent of [`__typematch_top_level_arms_branch_extract`], which has much more
/// documentation (they used to be one giant macro).
///
/// Calls:
///  * [__typematch_top_level_arms_branch_append] - next stage
///  * [__typematch_top_level_arms_branch_splay] - recursive mode optimisation
///
/// Called by:
///  * [__typematch_top_level_arms_branch_extract] - main entry point.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_top_level_arms_branch_splay {
    // Splay out the data from the current level
    //
    // Note that because this is "bulk" splaying, we can't macro-switch on the type branch info to
    // automatically eliminate branches which we know will be made unreachable later.
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            next_typeid_pattern: [direct {
                type_branches: [$($type_branch_info:tt)*],
                type_alias: $type_alias_info:tt,
                witness_or_ignore: $witness_or_ignore_info:tt
            }],
            append_tree: $append_tree:tt,
            leaf: $leaf:tt
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_append!{{
            partially_parsed_match_arm_specs: [$($({
                arm_prefix_data: $arm_prefix_data,
                append_tree: [
                    $append_tree;
                    {
                        // This is the actual data for each level
                        //
                        // Remember - these are all `tt`s. they contain the actual information for
                        // later parsing.
                        //
                        // the constraint is what we're splaying over
                        type_constraint: $type_branch_info,
                        type_alias: $type_alias_info,
                        witness_or_ignore: $witness_or_ignore_info
                    }
                ],
                leaf: $leaf,
                extra_data: []
            } /* type branch info splay */)*
            )* /* existing arrays with arm_prefix_data */],
            $($tail)*
        }}
    };

    // recursive direct-splay
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            next_typeid_pattern: [recurse {
                type_branches: [$($type_branch_info:tt)*],
                type_alias: $type_alias_info:tt,
                witness_or_ignore: $witness_or_ignore_info:tt
            } $next_typeid_pattern:tt],
            append_tree: $append_tree:tt,
            leaf: $leaf:tt
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_splay!{{
            partially_parsed_match_arm_specs: [$($({
                arm_prefix_data: $arm_prefix_data,
                // recurse in
                //
                // The next component in the cons-list is itself
                // of appropriate format to be passed directly
                next_typeid_pattern: $next_typeid_pattern,
                append_tree: [
                    $append_tree;
                    {
                        type_constraint: $type_branch_info,
                        type_alias: $type_alias_info,
                        witness_or_ignore: $witness_or_ignore_info
                    }
                ],
                leaf: $leaf
            })* /* type splay*/)* /* existing arrays with arm_prefix_data */],
            $($tail)*
        }}
    };
}

/// Subcomponent of [__typematch_top_level_arms_branch_extract] that executes commands to
/// add to the (now splayed out) match arm prefix data. This used to be part of one big macro, so
/// most of the documentation is in [__typematch_top_level_arms_branch_extract].
///
/// Calls:
/// * [__typematch_top_level_arms_branch_extract] - next stage
/// * [__typematch_top_level_arms_branch_append] - recursive action for very long append
///   command lists
///
/// Called by:
/// * [__typematch_top_level_arms_branch_splay]
#[doc(hidden)]
#[macro_export]
macro_rules!  __typematch_top_level_arms_branch_append {
    // Append the new branch info onto the prefix data, and repeat
    //
    // This has specialisations for all append list lengths up to 4, and then
    // a generic recursive one at 4 to account for things longer than that
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: [$($arm_prefix_data:tt)*],
            append_tree: [],
            leaf: $remaining_info:tt,
            extra_data: [$($extra_data:tt)*]
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_extract!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: [$($arm_prefix_data)* $($extra_data)*],
                leaf: $remaining_info
            })*],
            $($tail)*
        }}
    };
    // single one
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: [$($arm_prefix_data:tt)*],
            append_tree: [[];$next_data_0:tt],
            leaf: $remaining_info:tt,
            extra_data: [$($extra_data:tt)*]
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_extract!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: [$($arm_prefix_data)* $next_data_0 $($extra_data)*],
                leaf: $remaining_info
            })*],
            $($tail)*
        }}
    };
    // 2
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: [$($arm_prefix_data:tt)*],
            append_tree: [[[]; $next_data_0:tt];$next_data_1:tt],
            leaf: $remaining_info:tt,
            extra_data: [$($extra_data:tt)*]
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_extract!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: [
                    $($arm_prefix_data)*
                    $next_data_0
                    $next_data_1
                    $($extra_data)*
                ],
                leaf: $remaining_info
            })*],
            $($tail)*
        }}
    };
    // 3
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: [$($arm_prefix_data:tt)*],
            append_tree: [[[[]; $next_data_0:tt];$next_data_1:tt];$next_data_2:tt],
            leaf: $remaining_info:tt,
            extra_data: [$($extra_data:tt)*]
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_extract!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: [
                    $($arm_prefix_data)*
                    $next_data_0
                    $next_data_1
                    $next_data_2
                    $($extra_data)*
                ],
                leaf: $remaining_info
            })*],
            $($tail)*
        }}
    };
    // 4
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: [$($arm_prefix_data:tt)*],
            append_tree: [[[[[]; $next_data_0:tt];$next_data_1:tt];$next_data_2:tt];$next_data_3:tt],
            leaf: $remaining_info:tt,
            extra_data: [$($extra_data:tt)*]
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_extract!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: [
                    $($arm_prefix_data)*
                    $next_data_0
                    $next_data_1
                    $next_data_2
                    $next_data_3
                    $($extra_data)*
                ],
                leaf: $remaining_info
            })*],
            $($tail)*
        }}
    };
    // 4+ recursive
    ({
        partially_parsed_match_arm_specs: [$({
            arm_prefix_data: $arm_prefix_data:tt,
            append_tree: [[[[$rest:tt; $next_data_0:tt];$next_data_1:tt];$next_data_2:tt];$next_data_3:tt],
            leaf: $remaining_info:tt,
            extra_data: [$($extra_data:tt)*]
        })*],
        $($tail:tt)*
    }) => {
        $crate::__typematch_top_level_arms_branch_append!{{
            partially_parsed_match_arm_specs: [$({
                arm_prefix_data: $arm_prefix_data,
                append_tree: $rest,
                leaf: $remaining_info,
                extra_data: [
                    $next_data_0
                    $next_data_1
                    $next_data_2
                    $next_data_3
                    $($extra_data)*
                ]
            })*],
            $($tail)*
        }}
    };
}

/// This directly associates typeid generator information per-index with the
/// various match arm infos per-index into one iterable chunk
///
/// If you're seeing errors here, it's probably because the pattern specifications you've written
/// have a different number of entries than the amount of things you're actually matching on
///
/// Called by:
/// * [__typematch_top_level_arms_branch_extract]
///
/// Calls:
/// * [__typematch_generate_match]
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_splay_typeid_generator_info {
    ({
        match_arm_infos: [$({
            arm_index_data: [$({
                type_constraint: $type_branch_info:tt,
                type_alias: $type_alias_info:tt,
                witness_or_ignore: $witness_or_ignore_info:tt
            })*],
            typeid_generator_info: [$({
                matchmode: $matchmode:ident $matchmode_data:tt,
                expr: $typeid_expr:expr
            })*],
            output_expr: {$output_expr:expr}
        })*],
        pre_match_statements: $pre_match_statements:tt,
        matched_expression: $match_expression_bundle:tt
    }) => {
         $crate::__typematch_generate_match!{
            pre_match_statements: $pre_match_statements,
            matched_expression_bundle: $match_expression_bundle,
            arm_data: [$({
                index_data: [$({
                    type_constraint_bundle: $type_branch_info,
                    type_alias_bundle: $type_alias_info,
                    witness_or_ignore_bundle: $witness_or_ignore_info,
                    matching: $matchmode $matchmode_data,
                    expr_of_matching_typeid: $typeid_expr
                })*],
                output_expr: {$output_expr}
            })*]
         }
    };
}

/// This is the "submacro" which actually generates the match statement and surrounding information
///
/// Beyond this point, the various macros that are generic across the pattern-part of a match arm
/// and the expression-part of a match arm are likely to carry an "arm component selector" that is
/// one of the following:
/// * meta - construct a singular attribute for an arm. [crate::__macros_force_meta] might be useful
///   for implementations. You must provide exactly one attribute (this is required to stop issues
///   with intermediary products). For things you want to include unconditionally, just use
///   `cfg(all())`, and things you want to delete unconditionally, use `cfg(any())`
///   NOTE: you can't actually generate meta attributes like this, sadly. This means that we rely
///   on the compiler to recognise `if false` match branches to never be possible.
/// * pattern - the part that actually matches things.
/// * pattern_guard - the part of the pattern after the if-statement.
/// * expression - the output expression of the arm
///
/// Something important to note is that the syntax of the original macro forces the user to provide
/// a catchall pattern. This is important, because, Rust does not recognise `if true` guards as
/// infallible, and it is not possible in the individual arms to generate the guard conditionally,
/// which means that all generated arms have a guard and can't satisfy the `match`s exhaustivity
/// requirement.  
///
/// This is because it's not possible to do "bulk detection" of any infallible patterns. If that
/// was possible to do efficiently, we could split out fallible and infallible and do the match
/// arms one after the other.
///
/// Called by:
/// * [__typematch_splay_typeid_generator_info] - entry point
///
/// Calls:
/// * [__typematch_arm_generate] - for each arm (one in each arm for each mode)
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_generate_match {
    (
        pre_match_statements: [$($pre_match_statements:tt)*],
        matched_expression_bundle: [$matched_expr:expr],
        arm_data: [$($single_arm_data:tt)*]
    ) => {{
        $($pre_match_statements)*
        match $matched_expr {$(
            /*
            #[$crate::__typematch_arm_generate!(@entry {
                arm_component: meta,
                capture_identifier: v,
                arm_data: $single_arm_data
            })]
            */
            $crate::__typematch_arm_generate!(@entry {
                arm_component: pattern,
                capture_identifier: v,
                arm_data: $single_arm_data
            }) if $crate::__typematch_arm_generate!(@entry {
                arm_component: pattern_guard,
                capture_identifier: v,
                arm_data: $single_arm_data
            }) => $crate::__typematch_arm_generate!(@entry {
                arm_component: expression,
                capture_identifier: v,
                arm_data: $single_arm_data
            }),)*
            // we can only do this because we know that the top-level macro forces users
            // to ensure there is an infallible pattern.
            //
            // This exists solely to satisfy the compiler's exhaustivity requirements because
            // it won't work with `if true` guards
            _ => $crate::_reexports::core::unreachable!("typematch should ensure user-provided fallback guard")
        }
    }};
}

/// Entry point for generating each [`crate::typematch`] match arm.
///
/// This essentially reorganises it's input for better tt-munching by [__typematch_arm_check_delete]
///
/// It does need an identifier as input that it can share between the pattern and pattern_guard
/// components.
///
/// Called by:
/// * [__typematch_generate_match]
///
/// Calls:
/// * [__typematch_arm_check_delete]
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_generate {
    // entry point
    (@entry {
        // This is `pattern`, `pattern_guard`, or `expression`
        arm_component: $arm_component:ident,
        capture_identifier: $capture_id:ident,
        arm_data: {
            index_data: [$({
                type_constraint_bundle: $type_constraint_info:tt,
                type_alias_bundle: $type_alias_info:tt,
                witness_or_ignore_bundle: $witness_or_ignore_info:tt,
                matching: $matchmode:ident $matchmode_data:tt,
                expr_of_matching_typeid: $typeid_expr:expr
            })*],
            output_expr: {$output_expr:expr}
        }
    }) => {
        $crate::__typematch_arm_check_delete!({
            arm_component: $arm_component,
            capture_identifier: $capture_id,
            unchecked_indices: [$({
                type_constraint_bundle: $type_constraint_info,
                witness_or_ignore_bundle: $witness_or_ignore_info,
                type_alias_bundle: $type_alias_info,
                matching: $matchmode $matchmode_data,
                expr_of_matching_typeid: $typeid_expr
            })*],
            checked_indices: [],
            output_expr: {$output_expr}
        })
    };
}

/// This is a tt-munching parser that checks an arm for deletion to jump to
/// [__typematch_arm_deleted] if that is the case.
///
/// This does deletion and some other classification, and emits errors for
/// confusing-but-syntactically-allowed constructs like fully empty patterns (it actually can't do
/// this at the moment due to limitations).
///
/// It then calls out to [__typematch_arm_create_components], which creates the actual components,
/// when it's done.
///
/// The classification itself is quite complex, because we had to avoid parsing so much earlier -
/// see [__typematch_top_level_arms_syntax_split] for the format.
///
///
/// Called by:
/// * [__typematch_arm_generate]
///
/// Calls:
/// * [__typematch_arm_deleted] - for deleted arms
/// * [__typematch_arm_error] - for confusing empty patterns that shouldn't be
///   allowed but can't be removed earlier syntactically.
/// * [__typematch_arm_create_components] - when it's done checking the components and formatting
///   them into constrained/unconstrained things with uniform structure, this actually creates the
///   various arm components.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_check_delete {
    // Confusing case of a completely empty pattern
    // error out.
    //
    // NOTE - this cannot actually detect empty patterns! We can't even capture _ as a `:pat`
    // fragment or a `:pat_param` fragment!, which means we have no way to actually construct
    // the tokens per-index-pattern and check for empty per-index-patterns.
    /*
    ({
        arm_component: $component:ident,
        capture_identifier: $capture_id:ident,
        unchecked_indices: [{
            type_constraint_bundle: [],
            witness_or_ignore_bundle: [],
            type_alias_bundle: $type_alias_info:tt,
            matching: $matchmode:ident $matchmode_data:tt,
            expr_of_matching_typeid: $typeid_expr:expr
        } $($remaining_unchecked_indices:tt)*],
        checked_indices: [$($checked:tt)*],
        output_expr: $output_expr:expr
    }) => {
        $crate::__typematch_arm_error!(arm_component: $component
            "confusing empty typematch constraint detected - have you put two commas next to each other or a bare `type alias = ` with nothing after and no capture?"
        )
    };*/


    // This is what is the case when we're done.
    //
    // Call out to the main construction mechanism
    ({
        arm_component: $component:ident,
        capture_identifier: $capture_id:ident,
        unchecked_indices: [],
        checked_indices: $checked:tt,
        output_expr: {$output_expr:expr}
    }) => {
        $crate::__typematch_arm_create_components!({
            arm_component: $component,
            capture_identifier: $capture_id,
            indices: $checked,
            output_expr: {$output_expr}
        })
    };


    // The not-deletion matcher for normal branches with a particular unconstrained bit
    //
    // This is the first part that does some partial analysis of other constraint components.
    ({
        arm_component: $component:ident,
        capture_identifier: $capture_id:ident,
        unchecked_indices: [{
            // This is the "unconditional" one. If this is present without the delete marker,
            // then this is definitely some form of unconstrained type specifier.
            type_constraint_bundle: [ [u] ],
            // if this is not empty, it contains an identifier (which can't be `_` because
            // that's a pattern!). If it is empty, then it's empty.
            witness_or_ignore_bundle:[$($witness:ident)?],
            // Type aliases are allowed in unconstrained components but only for type-constrained
            // data. We check this later
            type_alias_bundle: $type_alias_bundle:tt,
            matching: $matchmode:ident $matchmode_data:tt,
            // Typeid expression that always matches.
            expr_of_matching_typeid: $typeid_expr:expr
        } $($remaining_unchecked_indices:tt)*],
        checked_indices: [$($checked:tt)*],
        output_expr: {$output_expr:expr}
    }) => {
       $crate::__typematch_arm_check_delete!({
            arm_component: $component,
            capture_identifier: $capture_id,
            unchecked_indices: [$($remaining_unchecked_indices)*],
            // Put at the end
            checked_indices: [$($checked)* {
                unconstrained {
                    witness_bundle: [$($witness)?],
                    type_alias_bundle: $type_alias_bundle,
                    matching: $matchmode $matchmode_data,
                    // The expression that should be in the guard-equality tuple for
                    // this index
                    //
                    // In this case, because of the lack of constraint, this should be
                    // the typeid expression
                    equality_match_expr: $typeid_expr,
                    extra: {}
                }
            }],
            output_expr: {$output_expr}
       })
    };
    // The deletion matcher
    ({
        arm_component: $component:ident,
        capture_identifier: $capture_id:ident,
        unchecked_indices: [{
            type_constraint_bundle: [ [u] $_del_marker:tt],
            $($_tail_data:tt)*
        } $($_other_unchecked_indices:tt)*],
        $($_rest:tt)*
    }) => {
        $crate::__typematch_arm_deleted!(arm_component: $component)
    };
    // The matcher for type constraint expressions.
    ({
        arm_component: $component:ident,
        capture_identifier: $capture_id:ident,
        unchecked_indices: [{
            type_constraint_bundle: [[t: $constraining_type:ty]],
            witness_or_ignore_bundle: [$($witness:ident)?],
            type_alias_bundle: $type_alias_bundle:tt,
            matching: $matchmode:ident $matchmode_data:tt,
            // Typeid expression that always matches.
            expr_of_matching_typeid: $typeid_expr:expr
        } $($other_unchecked_indices:tt)*],
        checked_indices: [$($checked:tt)*],
        output_expr: {$output_expr:expr}
    }) => {
        $crate::__typematch_arm_check_delete!({
            arm_component: $component,
            capture_identifier: $capture_id,
            unchecked_indices: [$($other_unchecked_indices)*],
            checked_indices: [$($checked)* {
                constrained {
                    witness_bundle: [$($witness)?],
                    type_alias_bundle: $type_alias_bundle,
                    matching: $matchmode $matchmode_data,
                    // The expression that should be in the guard-equality tuple for
                    // this index. In this case, that is the typeid of the constraining type.
                    equality_match_expr: {
                        $crate::_reexports::core::any::TypeId::of::<$constraining_type>()
                    },
                    extra: {
                        type_constraint: $constraining_type
                    }
                }
            }],
            output_expr: {$output_expr}
        })
    };

}

/// Takes the generated and classified parts described by [__typematch_arm_check_delete], and
/// actually creates the components. This provides certain very useful capabilities - for example,
/// it does shorthand match stuff for fully-unconstrained arms, and is capable of creating the
/// `pattern`, `pattern_guard`, and `meta` components directly, as the format produced by the
/// previous macro is amenable to efficient and uniform construction of those.
///
/// Called by:
/// * [__typematch_arm_check_delete]
///
/// Calls:
/// * [__typematch_arm_make_witness] - construct witnesses for those constraints requesting them
/// * [__typematch_arm_make_type_alias] - construct type aliases for those constraints requesting them.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_create_components {
    // At this point we know we aren't a deleted arm. However, we still need to provide a
    // `meta` component. To do this, we use `cfg(all())`, which is always true.
    /*
    ({
        arm_component: meta,
        capture_identifier: $capture_id:ident,
        indices: $_indices:tt,
        output_expr: $output_expr:expr
    }) => { $crate::__macros_force_meta!(cfg(all())) };
    */

    // If all elements are unconstrained, then we can make the pattern and pattern guard
    // unconditional as well. Witnesses are not actually constructed using the captured data
    // anyway, so it is fine.
    ({
        arm_component: pattern,
        capture_identifier: $capture_id:ident,
        indices: [$({ unconstrained $_tt:tt })*],
        output_expr: {$output_expr:expr}
    }) => {
        _
    };
    // Unconstrained arms have no need for comparisons at all. Make the guard true.
    ({
        arm_component: pattern_guard,
        capture_identifier: $capture_id:ident,
        indices: [$({ unconstrained $_tt:tt })*],
        output_expr: {$output_expr:expr}
    }) => {
        true
    };

    // This is the normal case
    ({
        arm_component: pattern,
        capture_identifier: $capture_id:ident,
        indices: [$($checked:tt)*],
        output_expr: {$output_expr:expr}
    }) => {
        $crate::__macros_force_pat!($capture_id)
    };

    // Pattern guard - constructed by extracting the equality_match_expr
    ({
        arm_component: pattern_guard,
        capture_identifier: $capture_id:ident,
        indices: [$({ $_constrain_or_not:ident {
            witness_bundle: $_witness_bundle:tt,
            type_alias_bundle: $_type_alias_bundle:tt,
            matching: $matchmode:ident $matchmode_data:tt,
            equality_match_expr: $equality_match_expr:expr,
            extra: $_extra:tt
        }})*],
        output_expr: {$output_expr:expr}
    }) => {
        { $capture_id == ($($equality_match_expr,)*) }
    };

    // Expression - now we need to construct the witnesses and type aliases.
    //
    // Something important to note here is that we *only invoke the given macros when
    // a witness is requested or a type alias is requested*. This means those macros need
    // not focus on sanitization and can actually just cover all the cases nicely.
    //
    // Furthermore, those macros don't have to deal with anything involving witness or type alias
    // names at all. To deal with the constrained/unconstrained case, they simply can take the
    // constrained/unconstrained thing at the start.
    ({
        arm_component: expression,
        capture_identifier: $_capture_id:ident,
        indices: [$({ $constrain_or_not:ident {
            witness_bundle: [$($witness:ident)?],
            type_alias_bundle: [$($type_alias_name:ident)?],
            matching: $matchmode:ident $matchmode_data:tt,
            equality_match_expr: $_equality_match_expr:expr,
            extra: $constraint_data:tt
        }})*],
        output_expr: {$output_expr:expr}
    }) => {{
        $(
            $(let $witness = $crate::__typematch_arm_make_witness!(
                $constrain_or_not
                $matchmode
                $matchmode_data
                $constraint_data
            );)?
            $(type $type_alias_name = $crate::__typematch_arm_make_type_alias!(
                $constrain_or_not
                $matchmode
                $matchmode_data
                $constraint_data
            );)?
        )*
        $output_expr
    }};
}

/// Macro that actually makes the witness value directly if possible.
///
/// Does not need to worry about the witness name. It receives the constrained/unconstrained
/// information first, then the type of matching it does, then the data for each. This is for easy
/// matching on constrained/unconstrained and then ty/anyref/anymut/etc., and can let nice errors
/// be generated quickly.
///
/// Actual params look like:
/// * `constrained/unconstrained`
/// * `ty/anyref/anymut/etc.` (matching mode)
/// * the data for the matching mode
/// * constraint extra data (often less relevant, so dumped at the end
///
/// Called by:
/// * [__typematch_arm_create_components]
///
/// Calls:
/// * Nothing, basically, other than [crate::__macros_compile_error] for error reporting.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_make_witness {
    // For constrained type matchers, we can create live witnesses
    (constrained ty { $source_ty:ty } { type_constraint: $target_ty:ty }) => {
        $crate::_reexports::cisness::LiveWitness::<$source_ty, $target_ty>::only_executed_if_same()
    };
    // Inverse direction ty
    (constrained out_ty { $target_ty:ty } { type_constraint: $source_ty:ty }) => {
        $crate::_reexports::cisness::LiveWitness::<$source_ty, $target_ty>::only_executed_if_same()
    };
    // For constrained value-type matchers, we create live witnesses but then use them
    // to transform the actual values.
    //
    // When dealing with ones without explicit type ascription, we deduce from the reference
    (constrained val { val_id: $val_id:ident } { type_constraint: $target_ty:ty }) => {{
        let live_witness =
            $crate::_deduce_witness::deduce_livewitness_from_ref::<$target_ty, _>(&$val_id);
        live_witness.owned($val_id)
    }};
    // val matchers with type ascription
    (constrained val { val_id: $val_id:ident, ty: $ascribed_ty:ty } { type_constraint: $target_ty:ty }) => {
        $crate::_reexports::cisness::LiveWitness::<$ascribed_ty, $target_ty>::only_executed_if_same(
        )
        .owned($val_id)
    };
    // For constrained anyref matchers, we downcast_ref and .expect()
    (constrained anyref { $anyref_var:ident } { type_constraint: $target_ty:ty }) => {
        $anyref_var
            .downcast_ref::<$target_ty>()
            .expect("match has checked typeid")
    };
    (constrained anymut { $anymut_var:ident } { type_constraint: $target_ty:ty }) => {
        $anymut_var
            .downcast_mut::<$target_ty>()
            .expect("match has checked typeid")
    };
    // For unconstrained type matchers, we also use different witnesses. For matching on an actual
    // type, we want to provide raw typeid.  For matching on anymut or anyref, we want to provide
    // that instead.
    (unconstrained ty { $source_ty:ty } $extra:tt) => {
        $crate::_reexports::core::any::TypeId::of::<$source_ty>()
    };
    (unconstrained out_ty { $target_ty:ty } $extra:tt) => {
        $crate::_reexports::core::any::TypeId::of::<$target_ty>()
    };
    // For unconstrained val, then we want to just provide the value directly as self-witness
    (unconstrained val { val_id: $val_id:ident $(, ty: $_ascribed_ty:ty)? } $extra:tt) => {
        $val_id
    };
    (unconstrained anyref { $anyref_var:ident } $extra:tt) => {
        $anyref_var
    };
    (unconstrained anymut { $anymut_var:ident } $extra:tt) => {
        $anymut_var
    };
}

/// Macro that makes the type alias type directly if possible.
///
/// Does not need to worry about the type alias name. It receives the constrained/unconstrained
/// information first, then the type of matching it does, then the data for each one. This is for
/// easy matching on constrained/unconstrained and then ty/anyref/anymut/etc., and can let nice
/// errors be generated quickly.
///
/// Actual params look like:
/// * `constrained/unconstrained`
/// * `ty/anyref/anymut/etc.` (matching mode)
/// * the data for the matching mode
/// * constraint extra data (often less relevant, so dumped at the end
///
/// Called by:
/// * [__typematch_arm_create_components]
///
/// Calls:
/// * Nothing, basically, other than [crate::__macros_compile_error] for error reporting.
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_make_type_alias {
    // When constrained, we can always make a type alias
    (constrained $matching:ident $matching_data:tt { type_constraint: $c_ty:ty }) => {
        $c_ty
    };
    // When unconstrained, we can only make a type alias if the thing we're matching on embeds a
    // type at compile time.
    (unconstrained val { val_id: $val_id:ident, ty: $ascribed_ty:ty } $extra:tt) => {
        $ascribed_ty
    };
    (unconstrained ty { $matched_ty:ty } $extra:tt) => {
        $matched_ty
    };
    (unconstrained out_ty { $matched_ty:ty } $extra:tt) => {
        $matched_ty
    };
}

/// Generate a deleted arm
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_deleted {
    /*
    (arm_component: meta) => {
        // Should just delete the arm from compilation entirely as
        // empty `any()` is never true
        $crate::__macros_force_meta!(cfg(any()))
    };
    */
    (arm_component: pattern) => {
        _
    };
    (arm_component: pattern_guard) => {
        false
    };
    (arm_component: expression) => {
        unreachable!("deleted match arm")
    };
}

/// Generate a nice compile_error directive for a typematch arm, but in *just* a single place.
///
/// This does not just delegate to [__typematch_arm_deleted] as that will silently use
/// cfg directives to delete the arm from the code, preventing compile errors.
///
/// This lets you provide the arm mode and then a string literal
#[doc(hidden)]
#[macro_export]
macro_rules! __typematch_arm_error {
    (arm_component: expression $message:literal) => {
        $crate::_reexports::core::compile_error!($message)
    };
    (arm_component: meta) => {};
    (arm_component: pattern) => {
        _
    };
    (arm_component: pattern_guard) => {
        true
    };
}

// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0/.