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
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
use super::ext::*;
use super::generics::ParsedGenerics;
use crate::util::*;
use itertools::*;
use proc_macro2::TokenStream;
use quote::*;
use std::collections::HashMap;
use syn::parse::{Parse, ParseStream};
use syn::*;

/// Describes information about a single trait.
pub struct TraitInfo {
    path: Path,
    ident: Ident,
    generics: ParsedGenerics,
    vtbl_name: Ident,
    ret_tmp_typename: Ident,
    ret_tmp_name: Ident,
    enable_vtbl_name: Ident,
    lc_name: Ident,
    vtbl_typename: Ident,
}

impl PartialEq for TraitInfo {
    fn eq(&self, o: &Self) -> bool {
        self.ident == o.ident
    }
}

impl Eq for TraitInfo {}

impl Ord for TraitInfo {
    fn cmp(&self, o: &Self) -> std::cmp::Ordering {
        self.ident.cmp(&o.ident)
    }
}

impl PartialOrd for TraitInfo {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl From<Path> for TraitInfo {
    fn from(in_path: Path) -> Self {
        let (path, ident, gens) =
            split_path_ident(&in_path).expect("Failed to split path by idents");

        let lc_ident = ident.to_string().to_lowercase();

        Self {
            vtbl_name: format_ident!("vtbl_{}", lc_ident),
            lc_name: format_ident!("{}", lc_ident),
            vtbl_typename: format_ident!("{}Vtbl", ident),
            ret_tmp_typename: format_ident!("{}RetTmp", ident),
            ret_tmp_name: format_ident!("ret_tmp_{}", lc_ident),
            enable_vtbl_name: format_ident!("enable_{}", ident.to_string().to_lowercase()),
            path,
            ident,
            generics: ParsedGenerics::from(gens.as_ref()),
        }
    }
}

/// Describes parse trait group, allows to generate code for it.
#[cfg_attr(feature = "unstable", allow(unused))]
pub struct TraitGroup {
    name: Ident,
    cont_name: Ident,
    generics: ParsedGenerics,
    mandatory_vtbl: Vec<TraitInfo>,
    optional_vtbl: Vec<TraitInfo>,
    ext_traits: HashMap<Ident, (Path, ItemTrait)>,
    extra_filler_traits: bool,
}

impl Parse for TraitGroup {
    fn parse(input: ParseStream) -> Result<Self> {
        let name = input.parse()?;

        let generics = input.parse()?;

        // TODO: parse associated type defs here
        parse_brace_content(input).ok();

        input.parse::<Token![,]>()?;
        let mandatory_traits = parse_maybe_braced::<Path>(input)?;

        input.parse::<Token![,]>()?;
        let optional_traits = parse_maybe_braced::<Path>(input)?;

        let ext_trait_defs = if input.parse::<Token![,]>().is_ok() {
            parse_maybe_braced::<ItemTrait>(input)?
        } else {
            vec![]
        };

        let mut ext_traits = HashMap::new();

        let mut mandatory_vtbl: Vec<TraitInfo> = mandatory_traits
            .into_iter()
            .map(prelude_remap)
            .map(TraitInfo::from)
            .collect();
        mandatory_vtbl.sort();

        let mut optional_vtbl: Vec<TraitInfo> = optional_traits
            .into_iter()
            .map(prelude_remap)
            .map(TraitInfo::from)
            .collect();
        optional_vtbl.sort();

        let store_exports = get_exports();
        let store_traits = get_store();

        let mut crate_path: Path = parse2(crate_path()).expect("Failed to parse crate path");

        if !crate_path.segments.empty_or_trailing() {
            crate_path.segments.push_punct(Default::default());
        }

        // Go through mand/opt vtbls and pick all external traits used out of there,
        // and then pick add those trait definitions to the ext_traits list from both
        // the input list, and the standard trait collection.
        for vtbl in mandatory_vtbl.iter_mut().chain(optional_vtbl.iter_mut()) {
            let is_ext = match (vtbl.path.leading_colon, vtbl.path.segments.first()) {
                (_, Some(x)) => x.ident == "ext",
                _ => false,
            };

            if !is_ext {
                continue;
            }

            // If the user has supplied a custom implementation.
            if let Some(tr) = ext_trait_defs.iter().find(|tr| tr.ident == vtbl.ident) {
                // Keep the leading colon so as to allow going from the root or relatively
                let leading_colon = std::mem::replace(&mut vtbl.path.leading_colon, None);

                let old_path = std::mem::replace(
                    &mut vtbl.path,
                    Path {
                        leading_colon,
                        segments: Default::default(),
                    },
                );

                for seg in old_path.segments.into_pairs().skip(1) {
                    match seg {
                        punctuated::Pair::Punctuated(p, punc) => {
                            vtbl.path.segments.push_value(p);
                            vtbl.path.segments.push_punct(punc);
                        }
                        punctuated::Pair::End(p) => {
                            vtbl.path.segments.push_value(p);
                        }
                    }
                }

                ext_traits.insert(tr.ident.clone(), (vtbl.path.clone(), tr.clone()));
            } else {
                // Check the store otherwise
                let tr = store_traits
                    .get(&(vtbl.path.clone(), vtbl.ident.clone()))
                    .or_else(|| {
                        store_exports.get(&vtbl.ident).and_then(|p| {
                            vtbl.path = p.clone();
                            store_traits.get(&(p.clone(), vtbl.ident.clone()))
                        })
                    });

                if let Some(tr) = tr {
                    // If we are in the store, we should push crate_path path to the very start
                    let old_path = std::mem::replace(&mut vtbl.path, crate_path.clone());
                    for seg in old_path.segments.into_pairs() {
                        match seg {
                            punctuated::Pair::Punctuated(p, punc) => {
                                vtbl.path.segments.push_value(p);
                                vtbl.path.segments.push_punct(punc);
                            }
                            punctuated::Pair::End(p) => {
                                vtbl.path.segments.push_value(p);
                            }
                        }
                    }
                    ext_traits.insert(tr.ident.clone(), (vtbl.path.clone(), tr.clone()));
                } else {
                    eprintln!(
                        "Could not find external trait {}. Not changing paths.",
                        vtbl.ident
                    );
                }
            }
        }

        let extra_filler_traits = if input.parse::<Token![,]>().is_ok() {
            input.parse::<LitBool>()?.value
        } else {
            true
        };

        let cont_name = format_ident!("{}Container", name);

        Ok(Self {
            name,
            cont_name,
            generics,
            mandatory_vtbl,
            optional_vtbl,
            ext_traits,
            extra_filler_traits,
        })
    }
}

/// Describes trait group to be implemented on a type.
#[cfg(not(feature = "unstable"))]
pub struct TraitGroupImpl {
    ty: Type,
    ty_generics: ParsedGenerics,
    generics: ParsedGenerics,
    group_path: Path,
    group: Ident,
    implemented_vtbl: Vec<TraitInfo>,
    fwd_implemented_vtbl: Option<Vec<TraitInfo>>,
}

#[cfg(not(feature = "unstable"))]
impl Parse for TraitGroupImpl {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut ty: Type = input.parse()?;

        // Parse generic arguments from the type.
        // Here we assume the last instance of AngleBracketed are generic arguments.
        let ty_gens = extract_generics(&mut ty);

        let mut ty_generics = ParsedGenerics::from(ty_gens.as_ref());

        input.parse::<Token![,]>()?;

        let group = input.parse()?;

        let (group_path, group, gens) = split_path_ident(&group)?;

        let generics = ParsedGenerics::from(gens.as_ref());

        let mut generics = match input.parse::<ParsedGenerics>() {
            Ok(ParsedGenerics {
                gen_where_bounds, ..
            }) => {
                parse_brace_content(input).ok();
                ParsedGenerics {
                    gen_where_bounds,
                    ..generics
                }
            }
            _ => generics,
        };

        generics.merge_and_remap(&mut ty_generics);

        let implemented_vtbl = if input.parse::<Token![,]>().is_ok() {
            let implemented_traits = parse_maybe_braced::<Path>(input)?;

            let mut implemented_vtbl: Vec<TraitInfo> = implemented_traits
                .into_iter()
                .map(prelude_remap)
                .map(ext_abs_remap)
                .map(From::from)
                .collect();

            implemented_vtbl.sort();

            implemented_vtbl
        } else {
            vec![]
        };

        let fwd_implemented_vtbl = if input.parse::<Token![,]>().is_ok() {
            let implemented_traits = parse_maybe_braced::<Path>(input)?;

            let mut implemented_vtbl: Vec<TraitInfo> = implemented_traits
                .into_iter()
                .map(prelude_remap)
                .map(ext_abs_remap)
                .map(From::from)
                .collect();

            implemented_vtbl.sort();

            Some(implemented_vtbl)
        } else {
            None
        };

        ty_generics.replace_on_type(&mut ty);
        ty_generics.extract_lifetimes(&ty);

        Ok(Self {
            ty,
            ty_generics,
            generics,
            group_path,
            group,
            implemented_vtbl,
            fwd_implemented_vtbl,
        })
    }
}

#[cfg(not(feature = "unstable"))]
impl TraitGroupImpl {
    /// Generate trait group conversion for a specific type.
    ///
    /// The type will have specified vtables implemented as a conversion function.
    #[cfg(feature = "unstable")]
    pub fn implement_group(&self) -> TokenStream {
        Default::default()
    }

    #[cfg(not(feature = "unstable"))]
    pub fn implement_group(&self) -> TokenStream {
        let crate_path = crate_path();

        let ctx_bound = super::traits::ctx_bound();

        let ty = &self.ty;

        let group = &self.group;
        let group_path = &self.group_path;
        let ParsedGenerics { gen_use, .. } = &self.generics;

        let ParsedGenerics {
            gen_declare,
            gen_where_bounds,
            mut life_declare,
            mut life_use,
            ..
        } = [&self.ty_generics, &self.generics]
            .iter()
            .copied()
            .collect();

        // If no lifetimes are used, default to 'cglue_a
        if life_use.is_empty() {
            assert!(life_declare.is_empty());
            let lifetime = Lifetime {
                apostrophe: proc_macro2::Span::call_site(),
                ident: format_ident!("cglue_a"),
            };
            life_use.push_value(lifetime.clone());
            life_declare.push_value(LifetimeDef {
                lifetime,
                attrs: Default::default(),
                bounds: Default::default(),
                colon_token: Default::default(),
            });
        }

        if !life_declare.trailing_punct() {
            life_declare.push_punct(Default::default());
        }

        if !life_use.trailing_punct() {
            life_use.push_punct(Default::default());
        }

        // Lifetime should always exist based on previous code
        let first_life = life_use.first().unwrap();

        let gen_lt_bounds = self.generics.declare_lt_for_all(&quote!(#first_life));
        let gen_sabi_bounds = self.generics.declare_sabi_for_all(&crate_path);

        let gen_where_bounds = quote! {
            #gen_where_bounds
            #gen_sabi_bounds
            #gen_lt_bounds
        };

        let filler_trait = format_ident!("{}VtableFiller", group);
        let vtable_type = format_ident!("{}Vtables", group);
        let cont_name = format_ident!("{}Container", group);

        let implemented_tables = TraitGroup::enable_opt_vtbls(self.implemented_vtbl.iter());
        let vtbl_where_bounds = TraitGroup::vtbl_where_bounds(
            self.implemented_vtbl.iter(),
            &cont_name,
            quote!(CGlueInst),
            quote!(CGlueCtx),
            &self.generics,
            Some(quote!(Self)).as_ref(),
            first_life,
        );

        let gen = quote! {
            impl<#life_declare CGlueInst: ::core::ops::Deref<Target = #ty>, CGlueCtx: #ctx_bound, #gen_declare>
                #group_path #filler_trait<#life_use CGlueInst, CGlueCtx, #gen_use> for #ty
            where #gen_where_bounds #vtbl_where_bounds {
                fn fill_table(table: #group_path #vtable_type<#life_use CGlueInst, CGlueCtx, #gen_use>) -> #group_path #vtable_type<#life_use CGlueInst, CGlueCtx, #gen_use> {
                    table #implemented_tables
                }
            }
        };

        if let Some(fwd_vtbl) = &self.fwd_implemented_vtbl {
            let fwd_filler_trait = format_ident!("{}FwdVtableFiller", group);

            let fwd_ty = quote!(#crate_path::forward::Fwd<&#first_life mut #ty>);

            let implemented_tables = TraitGroup::enable_opt_vtbls(fwd_vtbl.iter());
            let vtbl_where_bounds = TraitGroup::vtbl_where_bounds(
                fwd_vtbl.iter(),
                &cont_name,
                quote!(CGlueInst),
                quote!(CGlueCtx),
                &self.generics,
                Some(quote!(Self)).as_ref(),
                first_life,
            );

            quote! {
                #gen

                impl<#life_declare CGlueInst: ::core::ops::Deref<Target = #fwd_ty>, CGlueCtx: #ctx_bound, #gen_declare>
                    #group_path #fwd_filler_trait<#life_use CGlueInst, CGlueCtx, #gen_use> for #ty
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #crate_path::trait_group::CGlueObjBase,
                    #gen_where_bounds #vtbl_where_bounds
                {
                    fn fill_fwd_table(table: #group_path #vtable_type<#life_use CGlueInst, CGlueCtx, #gen_use>) -> #group_path #vtable_type<#life_use CGlueInst, CGlueCtx, #gen_use> {
                        table #implemented_tables
                    }
                }
            }
        } else {
            gen
        }
    }
}

pub struct TraitCastGroup {
    name: TokenStream,
    needed_vtbls: Vec<TraitInfo>,
}

pub enum CastType {
    Cast,
    AsRef,
    AsMut,
    Into,
    OnlyCheck,
}

impl Parse for TraitCastGroup {
    fn parse(input: ParseStream) -> Result<Self> {
        let name;

        if let Ok(expr) = input.parse::<Expr>() {
            name = quote!(#expr);
        } else {
            name = input.parse::<Ident>()?.into_token_stream();
        }

        let implemented_traits = input.parse::<TypeImplTrait>()?;

        let mut needed_vtbls: Vec<TraitInfo> = implemented_traits
            .bounds
            .into_iter()
            .filter_map(|b| match b {
                TypeParamBound::Trait(tr) => Some(tr.path),
                _ => None,
            })
            .map(From::from)
            .collect();

        needed_vtbls.sort();

        Ok(Self { name, needed_vtbls })
    }
}

impl TraitCastGroup {
    /// Generate a cast to a specific type.
    ///
    /// The type will have specified vtables implemented as a conversion function.
    pub fn cast_group(&self, cast: CastType) -> TokenStream {
        let prefix = match cast {
            CastType::Cast => "cast",
            CastType::AsRef => "as_ref",
            CastType::AsMut => "as_mut",
            CastType::Into => "into",
            CastType::OnlyCheck => "check",
        };

        let name = &self.name;
        let func_name = TraitGroup::optional_func_name(prefix, self.needed_vtbls.iter());

        quote! {
            (#name).#func_name()
        }
    }
}

impl TraitGroup {
    /// Identifier for optional group struct.
    ///
    /// # Arguments
    ///
    /// * `name` - base name of the trait group.
    /// * `postfix` - postfix to add after the naem, and before `With`.
    /// * `traits` - traits that are to be implemented.
    pub fn optional_group_ident<'a>(
        name: &Ident,
        postfix: &str,
        traits: impl Iterator<Item = &'a TraitInfo>,
    ) -> Ident {
        let mut all_traits = String::new();

        for TraitInfo { ident, .. } in traits {
            all_traits.push_str(&ident.to_string());
        }

        format_ident!("{}{}With{}", name, postfix, all_traits)
    }

    /// Get the name of the function for trait conversion.
    ///
    /// # Arguments
    ///
    /// * `prefix` - function name prefix.
    /// * `lc_names` - lowercase identifiers of the traits the function implements.
    pub fn optional_func_name<'a>(
        prefix: &str,
        lc_names: impl Iterator<Item = &'a TraitInfo>,
    ) -> Ident {
        let mut ident = format_ident!("{}_impl", prefix);

        for TraitInfo { lc_name, .. } in lc_names {
            ident = format_ident!("{}_{}", ident, lc_name);
        }

        ident
    }

    /// Generate function calls that enable individual functional vtables.
    ///
    /// # Arguments
    ///
    /// * `iter` - iterator of optional traits to enable
    pub fn enable_opt_vtbls<'a>(iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo {
            enable_vtbl_name, ..
        } in iter
        {
            ret.extend(quote!(.#enable_vtbl_name()));
        }

        ret
    }

    /// Generate full code for the trait group.
    ///
    /// This trait group will have all variants generated for converting, building, and
    /// converting it.
    pub fn create_group(&self) -> TokenStream {
        // Path to trait group import.
        let crate_path = crate::util::crate_path();

        let ctx_bound = super::traits::ctx_bound();

        let trg_path: TokenStream = quote!(#crate_path::trait_group);

        let c_void = crate::util::void_type();

        let name = &self.name;
        let cont_name = &self.cont_name;

        let ParsedGenerics {
            gen_declare,
            gen_use,
            gen_where_bounds,
            ..
        } = &self.generics;

        let gen_lt_bounds = self.generics.declare_lt_for_all(&quote!('cglue_a));
        let gen_sabi_bounds = self.generics.declare_sabi_for_all(&crate_path);

        // Structures themselves do not need StableAbi bounds, if layout_checks is on
        let gen_where_bounds_base = quote! {
            #gen_where_bounds
            #gen_lt_bounds
        };

        // If layout_checks is enabled, this will include StableAbi bounds
        let gen_where_bounds = quote! {
            #gen_where_bounds_base
            #gen_sabi_bounds
        };

        let cglue_a_lifetime = Lifetime {
            apostrophe: proc_macro2::Span::call_site(),
            ident: format_ident!("cglue_a"),
        };

        let mandatory_vtbl_defs = self.mandatory_vtbl_defs(self.mandatory_vtbl.iter());
        let optional_vtbl_defs = self.optional_vtbl_defs(quote!(CGlueInst), quote!(CGlueCtx));
        let optional_vtbl_defs_boxed = self.optional_vtbl_defs(
            quote!(#crate_path::boxed::CBox<'cglue_a, CGlueT>),
            quote!(#crate_path::trait_group::NoContext),
        );

        let mand_vtbl_default = self.mandatory_vtbl_defaults();
        let mand_ret_tmp_default = self.mandatory_ret_tmp_defaults();
        let full_opt_ret_tmp_default = Self::ret_tmp_defaults(self.optional_vtbl.iter());
        let default_opt_vtbl_list = self.default_opt_vtbl_list();
        let mand_vtbl_list = self.vtbl_list(self.mandatory_vtbl.iter());
        let full_opt_vtbl_list = self.vtbl_list(self.optional_vtbl.iter());
        let mandatory_as_ref_impls = self.mandatory_as_ref_impls(&trg_path);

        let get_container_impl = self.get_container_impl(name, &trg_path, &self.generics);

        let mandatory_internal_trait_impls = self.internal_trait_impls(
            name,
            self.mandatory_vtbl.iter(),
            &self.generics,
            &crate_path,
        );
        let vtbl_where_bounds = Self::vtbl_where_bounds(
            self.mandatory_vtbl.iter(),
            cont_name,
            quote!(CGlueInst),
            quote!(CGlueCtx),
            &self.generics,
            None,
            &cglue_a_lifetime,
        );
        let vtbl_where_bounds_noctx = Self::vtbl_where_bounds(
            self.mandatory_vtbl.iter(),
            cont_name,
            quote!(CGlueInst),
            quote!(#trg_path::NoContext),
            &self.generics,
            None,
            &cglue_a_lifetime,
        );
        let vtbl_where_bounds_boxed = Self::vtbl_where_bounds(
            self.mandatory_vtbl.iter(),
            cont_name,
            quote!(#crate_path::boxed::CBox<'cglue_a, CGlueT>),
            quote!(#crate_path::trait_group::NoContext),
            &self.generics,
            None,
            &cglue_a_lifetime,
        );
        let vtbl_where_bounds_ctxboxed = Self::vtbl_where_bounds(
            self.mandatory_vtbl.iter(),
            cont_name,
            quote!(#crate_path::boxed::CBox<'cglue_a, CGlueT>),
            quote!(CGlueCtx),
            &self.generics,
            None,
            &cglue_a_lifetime,
        );
        let ret_tmp_defs = self.ret_tmp_defs(self.optional_vtbl.iter());

        let mut enable_funcs = TokenStream::new();
        let mut enable_funcs_vtbl = TokenStream::new();

        #[cfg(feature = "layout_checks")]
        let derive_layouts = quote!(#[derive(::abi_stable::StableAbi)]);
        #[cfg(not(feature = "layout_checks"))]
        let derive_layouts = quote!();

        let all_gen_use = &gen_use;

        // Work around needless_update lint
        let fill_rest = if self.optional_vtbl.len() + self.mandatory_vtbl.len() > 1 {
            quote!(..self)
        } else {
            quote!()
        };

        for TraitInfo {
            enable_vtbl_name,
            vtbl_typename,
            vtbl_name,
            path,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in &self.optional_vtbl
        {
            for (funcs, fill_rest) in &mut [
                (&mut enable_funcs, &quote!(..self)),
                (&mut enable_funcs_vtbl, &fill_rest),
            ] {
                funcs.extend(quote! {
                    pub fn #enable_vtbl_name (self) -> Self
                        where &'cglue_a #path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #all_gen_use>, #gen_use>: Default {
                            Self {
                                #vtbl_name: Some(Default::default()),#fill_rest
                            }
                    }
                });
            }
        }

        let mut trait_funcs = TokenStream::new();

        let mut opt_structs = TokenStream::new();
        let mut opt_struct_imports = TokenStream::new();

        let impl_traits =
            self.impl_traits(self.mandatory_vtbl.iter().chain(self.optional_vtbl.iter()));

        let base_doc = format!(
            " Trait group potentially implementing `{}` traits.",
            impl_traits
        );
        let trback_doc = format!("be transformed back into `{}` without losing data.", name);
        let new_doc = format!(" Create new instance of {}.", name);

        let base_name_ref = format_ident!("{}BaseRef", name);
        let base_name_ctx_ref = format_ident!("{}BaseCtxRef", name);
        let base_name_arc_ref = format_ident!("{}BaseArcRef", name);
        let base_name_mut = format_ident!("{}BaseMut", name);
        let base_name_ctx_mut = format_ident!("{}BaseCtxMut", name);
        let base_name_arc_mut = format_ident!("{}BaseArcMut", name);
        let base_name_boxed = format_ident!("{}BaseBox", name);
        let base_name_arc_box = format_ident!("{}BaseArcBox", name);
        let base_name_ctx_box = format_ident!("{}BaseCtxBox", name);
        let opaque_name_ref = format_ident!("{}Ref", name);
        let opaque_name_ctx_ref = format_ident!("{}CtxRef", name);
        let opaque_name_arc_ref = format_ident!("{}ArcRef", name);
        let opaque_name_mut = format_ident!("{}Mut", name);
        let opaque_name_ctx_mut = format_ident!("{}CtxMut", name);
        let opaque_name_arc_mut = format_ident!("{}ArcMut", name);
        let opaque_name_boxed = format_ident!("{}Box", name);
        let opaque_name_arc_box = format_ident!("{}ArcBox", name);
        let opaque_name_ctx_box = format_ident!("{}CtxBox", name);

        #[cfg(not(feature = "unstable"))]
        let filler_trait = format_ident!("{}VtableFiller", name);
        #[cfg(not(feature = "unstable"))]
        let fwd_filler_trait = format_ident!("{}FwdVtableFiller", name);
        let vtable_type = format_ident!("{}Vtables", name);

        for traits in self
            .optional_vtbl
            .iter()
            .powerset()
            .filter(|v| !v.is_empty())
        {
            let func_name = Self::optional_func_name("cast", traits.iter().copied());
            let func_name_final = Self::optional_func_name("into", traits.iter().copied());
            let func_name_check = Self::optional_func_name("check", traits.iter().copied());
            let func_name_mut = Self::optional_func_name("as_mut", traits.iter().copied());
            let func_name_ref = Self::optional_func_name("as_ref", traits.iter().copied());
            let opt_final_name = Self::optional_group_ident(name, "Final", traits.iter().copied());
            let opt_name = Self::optional_group_ident(name, "", traits.iter().copied());
            let opt_vtbl_defs = self.mandatory_vtbl_defs(traits.iter().copied());
            let opt_mixed_vtbl_defs = self.mixed_opt_vtbl_defs(traits.iter().copied());

            let opt_vtbl_list = self.vtbl_list(traits.iter().copied());
            let opt_vtbl_unwrap = self.vtbl_unwrap_list(traits.iter().copied());
            let opt_vtbl_unwrap_validate = self.vtbl_unwrap_validate(traits.iter().copied());

            let mixed_opt_vtbl_unwrap = self.mixed_opt_vtbl_unwrap_list(traits.iter().copied());

            let get_container_impl = self.get_container_impl(&opt_name, &trg_path, &self.generics);

            let opt_as_ref_impls = self.as_ref_impls(
                &opt_name,
                self.mandatory_vtbl.iter().chain(traits.iter().copied()),
                &self.generics,
                &trg_path,
            );

            let opt_internal_trait_impls = self.internal_trait_impls(
                &opt_name,
                self.mandatory_vtbl.iter().chain(traits.iter().copied()),
                &self.generics,
                &crate_path,
            );

            let get_container_impl_final =
                self.get_container_impl(&opt_final_name, &trg_path, &self.generics);

            let opt_final_as_ref_impls = self.as_ref_impls(
                &opt_final_name,
                self.mandatory_vtbl.iter().chain(traits.iter().copied()),
                &self.generics,
                &trg_path,
            );

            let opt_final_internal_trait_impls = self.internal_trait_impls(
                &opt_final_name,
                self.mandatory_vtbl.iter().chain(traits.iter().copied()),
                &self.generics,
                &crate_path,
            );

            let impl_traits =
                self.impl_traits(self.mandatory_vtbl.iter().chain(traits.iter().copied()));

            let opt_final_doc = format!(
                " Final {} variant with `{}` implemented.",
                name, &impl_traits
            );
            let opt_final_doc2 = format!(
                " Retrieve this type using [`{}`]({}::{}) function.",
                func_name_final, name, func_name_final
            );

            let opt_doc = format!(
                " Concrete {} variant with `{}` implemented.",
                name, &impl_traits
            );
            let opt_doc2 = format!(" Retrieve this type using one of [`{}`]({}::{}), [`{}`]({}::{}), or [`{}`]({}::{}) functions.", func_name, name, func_name, func_name_mut, name, func_name_mut, func_name_ref, name, func_name_ref);

            // TODO: remove unused generics to remove need for phantom data

            opt_struct_imports.extend(quote! {
                #opt_final_name,
                #opt_name,
            });

            opt_structs.extend(quote! {

                // Final implementation - more compact layout.

                #[doc = #opt_final_doc]
                ///
                #[doc = #opt_final_doc2]
                #[repr(C)]
                #derive_layouts
                pub struct #opt_final_name<'cglue_a, CGlueInst: 'cglue_a, CGlueCtx: #ctx_bound, #gen_declare>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds_base
                {
                    #mandatory_vtbl_defs
                    #opt_vtbl_defs
                    container: #cont_name<CGlueInst, CGlueCtx, #gen_use>,
                }

                #get_container_impl_final

                #opt_final_as_ref_impls

                #opt_final_internal_trait_impls

                // Non-final implementation. Has the same layout as the base struct.

                #[doc = #opt_doc]
                ///
                #[doc = #opt_doc2]
                #[repr(C)]
                #derive_layouts
                pub struct #opt_name<'cglue_a, CGlueInst: 'cglue_a, CGlueCtx: #ctx_bound, #gen_declare>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds_base
                {
                    #mandatory_vtbl_defs
                    #opt_mixed_vtbl_defs
                    container: #cont_name<CGlueInst, CGlueCtx, #gen_use>,
                }

                unsafe impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare>
                    #trg_path::Opaquable for #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    type OpaqueTarget = #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>;
                }

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare>
                    From<#opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>> for #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    fn from(input: #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>) -> Self {
                        #trg_path::Opaquable::into_opaque(input)
                    }
                }

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare> #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                    where Self: #trg_path::Opaquable,
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    /// Cast back into the original group
                    pub fn upcast(self) -> <Self as #trg_path::Opaquable>::OpaqueTarget {
                        #trg_path::Opaquable::into_opaque(self)
                    }
                }

                #get_container_impl

                #opt_as_ref_impls

                #opt_internal_trait_impls
            });

            let func_final_doc1 = format!(
                " Retrieve a final {} variant that implements `{}`.",
                name, impl_traits
            );
            let func_final_doc2 = format!(
                " This consumes the `{}`, and outputs `Some(impl {})`, if all types are present.",
                name, impl_traits
            );

            let func_doc1 = format!(
                " Retrieve a concrete {} variant that implements `{}`.",
                name, impl_traits
            );
            let func_doc2 = format!(" This consumes the `{}`, and outputs `Some(impl {})`, if all types are present. It is possible to cast this type back with the `From` implementation.", name, impl_traits);

            let func_check_doc1 = format!(" Check whether {} implements `{}`.", name, impl_traits);
            let func_check_doc2 =
                " If this check returns true, it is safe to run consuming conversion operations."
                    .to_string();

            let func_mut_doc1 = format!(
                " Retrieve mutable reference to a concrete {} variant that implements `{}`.",
                name, impl_traits
            );
            let func_ref_doc1 = format!(
                " Retrieve immutable reference to a concrete {} variant that implements `{}`.",
                name, impl_traits
            );

            trait_funcs.extend(quote! {
                #[doc = #func_check_doc1]
                ///
                #[doc = #func_check_doc2]
                pub fn #func_name_check(&self) -> bool
                    where #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>: 'cglue_a + #impl_traits
                {
                    self.#func_name_ref().is_some()
                }

                #[doc = #func_final_doc1]
                ///
                #[doc = #func_final_doc2]
                pub fn #func_name_final(self) -> ::core::option::Option<impl 'cglue_a + #impl_traits>
                    where #opt_final_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>: 'cglue_a + #impl_traits
                {
                    let #name {
                        container,
                        #mand_vtbl_list
                        #opt_vtbl_list
                        ..
                    } = self;

                    Some(#opt_final_name {
                        container,
                        #mand_vtbl_list
                        #opt_vtbl_unwrap
                    })
                }

                #[doc = #func_doc1]
                ///
                #[doc = #func_doc2]
                pub fn #func_name(self) -> ::core::option::Option<#opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>>
                    where #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>: 'cglue_a + #impl_traits
                {
                    let #name {
                        container,
                        #mand_vtbl_list
                        #full_opt_vtbl_list
                    } = self;

                    Some(#opt_name {
                        container,
                        #mand_vtbl_list
                        #mixed_opt_vtbl_unwrap
                    })
                }

                #[doc = #func_mut_doc1]
                pub fn #func_name_mut<'b>(&'b mut self) -> ::core::option::Option<&'b mut (impl 'cglue_a + #impl_traits)>
                    where #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>: 'cglue_a + #impl_traits
                {
                    let #name {
                        container,
                        #mand_vtbl_list
                        #opt_vtbl_list
                        ..
                    } = self;

                    let _ = (#opt_vtbl_unwrap_validate);

                    // Safety:
                    //
                    // Structure layouts are fully compatible,
                    // optional reference validity was checked beforehand

                    unsafe {
                        (self as *mut Self as *mut #opt_name<CGlueInst, CGlueCtx, #gen_use>).as_mut()
                    }
                }

                #[doc = #func_ref_doc1]
                pub fn #func_name_ref<'b>(&'b self) -> ::core::option::Option<&'b (impl 'cglue_a + #impl_traits)>
                    where #opt_name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>: 'cglue_a + #impl_traits
                {
                    let #name {
                        #mand_vtbl_list
                        #opt_vtbl_list
                        ..
                    } = self;

                    let _ = (#opt_vtbl_unwrap_validate);

                    // Safety:
                    //
                    // Structure layouts are fully compatible,
                    // optional reference validity was checked beforehand

                    unsafe {
                        (self as *const Self as *const #opt_name<CGlueInst, CGlueCtx, #gen_use>).as_ref()
                    }
                }
            });
        }

        #[cfg(not(feature = "unstable"))]
        let (extra_filler_traits, filler_trait_imports) = if self.extra_filler_traits {
            let traits = quote! {
                pub trait #fwd_filler_trait<'cglue_a, CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #gen_declare>: 'cglue_a + Sized
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    fn fill_fwd_table(table: #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>) -> #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>;
                }

                impl<'cglue_a, CGlueInst: ::core::ops::Deref<Target = #crate_path::forward::Fwd<&'cglue_a mut CGlueT>>, CGlueT, CGlueCtx: #ctx_bound, #gen_declare>
                    #filler_trait<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                    for #crate_path::forward::Fwd<&'cglue_a mut CGlueT>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    CGlueT: #fwd_filler_trait<'cglue_a, CGlueInst, CGlueCtx, #gen_use>,
                    #gen_where_bounds
                {
                    fn fill_table(table: #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>) -> #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use> {
                        CGlueT::fill_fwd_table(table)
                    }
                }
            };

            let imports = quote! {
                #filler_trait,
                #fwd_filler_trait,
            };

            (traits, imports)
        } else {
            (quote!(), quote!(#filler_trait,))
        };

        #[cfg(feature = "unstable")]
        let filler_trait_imports = quote!();

        let submod_name = format_ident!("cglue_{}", name.to_string().to_lowercase());

        let cglue_obj_impl = self.cglue_obj_impl(&trg_path, &self.generics);

        #[cfg(feature = "unstable")]
        let cglue_inst_filler_trait_bound = quote!();
        #[cfg(not(feature = "unstable"))]
        let cglue_inst_filler_trait_bound =
            quote!(CGlueInst::Target: #filler_trait<'cglue_a, CGlueInst, CGlueCtx, #gen_use>,);
        #[cfg(feature = "unstable")]
        let create_vtbl = quote!(Default::default());
        #[cfg(not(feature = "unstable"))]
        let create_vtbl = quote!(CGlueInst::Target::fill_table(Default::default()));

        #[cfg(feature = "unstable")]
        let filler_trait_impl = quote!();
        #[cfg(not(feature = "unstable"))]
        let filler_trait_impl = quote! {
            pub trait #filler_trait<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare>: Sized
            where
                #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                #gen_where_bounds
            {
                fn fill_table(table: #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>) -> #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>;
            }

            #extra_filler_traits
        };

        quote! {

            #[doc(hidden)]
            pub use #submod_name::*;

            pub mod #submod_name {
                use super::*;

                pub use cglue_internal::{
                    #name,
                    #vtable_type,
                    #filler_trait_imports
                    #base_name_ref,
                    #base_name_ctx_ref,
                    #base_name_arc_ref,
                    #base_name_mut,
                    #base_name_ctx_mut,
                    #base_name_arc_mut,
                    #base_name_boxed,
                    #base_name_arc_box,
                    #base_name_ctx_box,
                    #opaque_name_ref,
                    #opaque_name_ctx_ref,
                    #opaque_name_arc_ref,
                    #opaque_name_mut,
                    #opaque_name_ctx_mut,
                    #opaque_name_arc_mut,
                    #opaque_name_boxed,
                    #opaque_name_arc_box,
                    #opaque_name_ctx_box,
                    #cont_name,
                    #opt_struct_imports
                };

                mod cglue_internal {
                use super::*;

                #[repr(C)]
                #[doc = #base_doc]
                ///
                /// Optional traits are not implemented here, however. There are numerous conversion
                /// functions available for safely retrieving a concrete collection of traits.
                ///
                /// `check_impl_` functions allow to check if the object implements the wanted traits.
                ///
                /// `into_impl_` functions consume the object and produce a new final structure that
                /// keeps only the required information.
                ///
                /// `cast_impl_` functions merely check and transform the object into a type that can
                #[doc = #trback_doc]
                ///
                /// `as_ref_`, and `as_mut_` functions obtain references to safe objects, but do not
                /// perform any memory transformations either. They are the safest to use, because
                /// there is no risk of accidentally consuming the whole object.
                #derive_layouts
                pub struct #name<'cglue_a, CGlueInst: 'cglue_a, CGlueCtx: #ctx_bound, #gen_declare>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds_base
                {
                    #mandatory_vtbl_defs
                    #optional_vtbl_defs
                    container: #cont_name<CGlueInst, CGlueCtx, #gen_use>,
                }

                #get_container_impl

                #[repr(C)]
                #derive_layouts
                pub struct #cont_name<CGlueInst, CGlueCtx: #ctx_bound, #gen_declare>
                {
                    instance: CGlueInst,
                    context: CGlueCtx,
                    #ret_tmp_defs
                }

                #cglue_obj_impl

                unsafe impl<CGlueInst: #trg_path::Opaquable, CGlueCtx: #ctx_bound, #gen_declare>
                    #trg_path::Opaquable for #cont_name<CGlueInst, CGlueCtx, #gen_use>
                {
                    type OpaqueTarget = #cont_name<CGlueInst::OpaqueTarget, CGlueCtx, #gen_use>;
                }

                #[repr(C)]
                #derive_layouts
                pub struct #vtable_type<'cglue_a, CGlueInst: 'cglue_a, CGlueCtx: #ctx_bound, #gen_declare>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds_base
                {
                    #mandatory_vtbl_defs
                    #optional_vtbl_defs
                }

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare> Default
                    for #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #vtbl_where_bounds #gen_where_bounds
                {
                    fn default() -> Self {
                        Self {
                            #mand_vtbl_default
                            #default_opt_vtbl_list
                        }
                    }
                }

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare> #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    #enable_funcs
                }

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare> #vtable_type<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    #enable_funcs_vtbl
                }

                #filler_trait_impl

                pub type #base_name_boxed<'cglue_a, CGlueT, #gen_use>
                    = #base_name_ctx_box<'cglue_a, CGlueT, #crate_path::trait_group::NoContext, #gen_use>;

                pub type #base_name_ctx_box<'cglue_a, CGlueT, CGlueCtx, #gen_use>
                    = #name<'cglue_a, #crate_path::boxed::CBox<'cglue_a, CGlueT>, CGlueCtx, #gen_use>;

                pub type #base_name_arc_box<'cglue_a, CGlueT, CGlueArcTy, #gen_use>
                    = #base_name_ctx_box<'cglue_a, CGlueT, #crate_path::arc::CArc<CGlueArcTy>, #gen_use>;

                pub type #base_name_ref<'cglue_a, CGlueT, #gen_use>
                    = #name<'cglue_a, &'cglue_a CGlueT, #crate_path::trait_group::NoContext, #gen_use>;

                pub type #base_name_ctx_ref<'cglue_a, CGlueT, CGlueCtx, #gen_use>
                    = #name<'cglue_a, &'cglue_a CGlueT, CGlueCtx, #gen_use>;

                pub type #base_name_arc_ref<'cglue_a, CGlueT, CGlueArcTy, #gen_use>
                    = #name<'cglue_a, &'cglue_a CGlueT, #crate_path::arc::CArc<CGlueArcTy>, #gen_use>;

                pub type #base_name_mut<'cglue_a, CGlueT, #gen_use>
                    = #name<'cglue_a, &'cglue_a mut CGlueT, #crate_path::trait_group::NoContext, #gen_use>;

                pub type #base_name_ctx_mut<'cglue_a, CGlueT, CGlueCtx, #gen_use>
                    = #name<'cglue_a, &'cglue_a mut CGlueT, CGlueCtx, #gen_use>;

                pub type #base_name_arc_mut<'cglue_a, CGlueT, CGlueArcTy, #gen_use>
                    = #name<'cglue_a, &'cglue_a mut CGlueT, #crate_path::arc::CArc<CGlueArcTy>, #gen_use>;

                pub type #opaque_name_boxed<'cglue_a, #gen_use>
                    = #base_name_boxed<'cglue_a, #c_void, #gen_use>;

                pub type #opaque_name_ref<'cglue_a, #gen_use>
                    = #base_name_ref<'cglue_a, #c_void, #gen_use>;

                pub type #opaque_name_ctx_ref<'cglue_a, CGlueCtx, #gen_use>
                    = #base_name_ctx_ref<'cglue_a, #c_void, CGlueCtx, #gen_use>;

                pub type #opaque_name_arc_ref<'cglue_a, #gen_use>
                    = #base_name_arc_ref<'cglue_a, #c_void, #c_void, #gen_use>;

                pub type #opaque_name_mut<'cglue_a, #gen_use>
                    = #base_name_mut<'cglue_a, #c_void, #gen_use>;

                pub type #opaque_name_ctx_mut<'cglue_a, CGlueCtx, #gen_use>
                    = #base_name_ctx_mut<'cglue_a, #c_void, CGlueCtx, #gen_use>;

                pub type #opaque_name_arc_mut<'cglue_a, #gen_use>
                    = #base_name_arc_mut<'cglue_a, #c_void, #c_void, #gen_use>;

                pub type #opaque_name_ctx_box<'cglue_a, CGlueCtx, #gen_use>
                    = #base_name_ctx_box<'cglue_a, #c_void, CGlueCtx, #gen_use>;

                pub type #opaque_name_arc_box<'cglue_a, #gen_use>
                    = #base_name_arc_box<'cglue_a, #c_void, #c_void, #gen_use>;


                impl<'cglue_a, CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #gen_declare>
                    From<(CGlueInst, CGlueCtx)> for #cont_name<CGlueInst, CGlueCtx, #gen_use>
                where
                    Self: #trg_path::CGlueObjBase
                {
                    fn from((instance, context): (CGlueInst, CGlueCtx)) -> Self {
                        Self {
                            instance,
                            context,
                            #mand_ret_tmp_default
                            #full_opt_ret_tmp_default
                        }
                    }
                }

                impl<'cglue_a, CGlueT, CGlueCtx: #ctx_bound, #gen_declare>
                    From<(CGlueT, CGlueCtx)> for #cont_name<#crate_path::boxed::CBox<'cglue_a, CGlueT>, CGlueCtx, #gen_use>
                where
                    Self: #trg_path::CGlueObjBase
                {
                    fn from((this, context): (CGlueT, CGlueCtx)) -> Self {
                        Self::from((#crate_path::boxed::CBox::from(this), context))
                    }
                }

                impl<'cglue_a, CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #gen_declare>
                    From<#cont_name<CGlueInst, CGlueCtx, #gen_use>> for #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #cglue_inst_filler_trait_bound
                    #vtbl_where_bounds #gen_where_bounds
                {
                    fn from(container: #cont_name<CGlueInst, CGlueCtx, #gen_use>) -> Self {
                        let vtbl = #create_vtbl;

                        let #vtable_type {
                            #mand_vtbl_list
                            #full_opt_vtbl_list
                        } = vtbl;

                        Self {
                            container,
                            #mand_vtbl_list
                            #full_opt_vtbl_list
                        }
                    }
                }

                impl<'cglue_a, CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #gen_declare>
                    From<(CGlueInst, CGlueCtx)> for #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    Self: From<#cont_name<CGlueInst, CGlueCtx, #gen_use>>,
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #vtbl_where_bounds #gen_where_bounds
                {
                    fn from((instance, context): (CGlueInst, CGlueCtx)) -> Self {
                        Self::from(#cont_name::from((instance, context)))
                    }
                }

                impl<'cglue_a, CGlueT, #gen_declare>
                    From<CGlueT> for #name<'cglue_a, #crate_path::boxed::CBox<'cglue_a, CGlueT>, #crate_path::trait_group::NoContext, #gen_use>
                where
                    Self: From<(#crate_path::boxed::CBox<'cglue_a, CGlueT>, #crate_path::trait_group::NoContext)>,
                    #vtbl_where_bounds_boxed #gen_where_bounds
                {
                    fn from(instance: CGlueT) -> Self {
                        Self::from((#crate_path::boxed::CBox::from(instance), Default::default()))
                    }
                }

                impl<'cglue_a, CGlueInst: core::ops::Deref, #gen_declare> From<CGlueInst>
                    for #name<'cglue_a, CGlueInst, #trg_path::NoContext, #gen_use>
                where
                    Self: From<(CGlueInst, #crate_path::trait_group::NoContext)>,
                    #cont_name<CGlueInst, #trg_path::NoContext, #gen_use>: #trg_path::CGlueObjBase,
                    #vtbl_where_bounds_noctx #gen_where_bounds
                {
                    fn from(instance: CGlueInst) -> Self {
                        Self::from((instance, Default::default()))
                    }
                }

                impl<'cglue_a, CGlueT, CGlueCtx: #ctx_bound, #gen_declare> From<(CGlueT, CGlueCtx)>
                    for #name<'cglue_a, #crate_path::boxed::CBox<'cglue_a, CGlueT>, CGlueCtx, #gen_use>
                where
                    Self: From<(#crate_path::boxed::CBox<'cglue_a, CGlueT>, CGlueCtx)>,
                    #cont_name<#crate_path::boxed::CBox<'cglue_a, CGlueT>, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #vtbl_where_bounds_ctxboxed #gen_where_bounds
                {
                    fn from((this, context): (CGlueT, CGlueCtx)) -> Self {
                        Self::from((#crate_path::boxed::CBox::from(this), context))
                    }
                }

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_declare>
                    #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #vtbl_where_bounds #gen_where_bounds
                {
                    #[doc = #new_doc]
                    pub fn new(instance: CGlueInst, context: CGlueCtx, #optional_vtbl_defs) -> Self
                        where #vtbl_where_bounds
                    {
                        Self {
                            container: #cont_name {
                                instance,
                                context,
                                #mand_ret_tmp_default
                                #full_opt_ret_tmp_default
                            },
                            #mand_vtbl_default
                            #full_opt_vtbl_list
                        }
                    }
                }

                impl<'cglue_a, CGlueT, #gen_declare> #name<'cglue_a, #crate_path::boxed::CBox<'cglue_a, CGlueT>, #crate_path::trait_group::NoContext, #gen_use>
                    where #gen_where_bounds
                {
                    #[doc = #new_doc]
                    ///
                    /// `instance` will be moved onto heap.
                    pub fn new_boxed(this: CGlueT, #optional_vtbl_defs_boxed) -> Self
                        where #vtbl_where_bounds_boxed
                    {
                        Self::new(From::from(this), Default::default(), #full_opt_vtbl_list)
                    }
                }

                /// Convert into opaque object.
                ///
                /// This is the prerequisite for using underlying trait implementations.
                unsafe impl<'cglue_a, CGlueInst: #trg_path::Opaquable, CGlueCtx: #ctx_bound, #gen_declare>
                    #trg_path::Opaquable for #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #cont_name<CGlueInst::OpaqueTarget, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    type OpaqueTarget = #name<'cglue_a, CGlueInst::OpaqueTarget, CGlueCtx, #gen_use>;
                }

                impl<
                    'cglue_a,
                    CGlueInst, //: ::core::ops::Deref
                    CGlueCtx: #ctx_bound,
                    #gen_declare
                >
                    #name<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                    #gen_where_bounds
                {
                    #trait_funcs
                }

                #mandatory_as_ref_impls

                #mandatory_internal_trait_impls

                #opt_structs
            }
            }
        }
    }

    fn internal_trait_impls<'a>(
        &'a self,
        self_ident: &Ident,
        iter: impl Iterator<Item = &'a TraitInfo>,
        all_generics: &ParsedGenerics,
        crate_path: &TokenStream,
    ) -> TokenStream {
        let mut ret = TokenStream::new();

        let cont_name = &self.cont_name;

        let ctx_bound = super::traits::ctx_bound();

        let ParsedGenerics { gen_use, .. } = all_generics;

        for TraitInfo {
            path,
            ident,
            generics:
                ParsedGenerics {
                    life_use: tr_life_use,
                    gen_use: tr_gen_use,
                    ..
                },
            ..
        } in iter
        {
            if let Some((ext_path, tr_info)) = self.ext_traits.get(ident) {
                let mut impls = TokenStream::new();

                let ext_name = format_ident!("{}Ext", ident);

                let (funcs, _, _) = super::traits::parse_trait(
                    tr_info,
                    crate_path,
                    false,
                    super::traits::process_item,
                );

                for func in &funcs {
                    func.int_trait_impl(Some(ext_path), &ext_name, &mut impls);
                }

                let gen = quote! {
                    impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #gen_use>
                        #path #ident <#tr_life_use #tr_gen_use> for #self_ident<'cglue_a, CGlueInst, CGlueCtx, #gen_use>
                    where
                        #cont_name<CGlueInst, CGlueCtx, #gen_use>: #crate_path::trait_group::CGlueObjBase,
                        Self: #ext_path #ext_name<#tr_life_use #tr_gen_use>
                    {
                        #impls
                    }
                };

                ret.extend(gen);
            }
        }

        ret
    }

    /// Required vtable definitions.
    ///
    /// Required means they must be valid - non-Option.
    ///
    /// # Arguments
    ///
    /// * `iter` - can be any list of traits.
    ///
    fn mandatory_vtbl_defs<'a>(&'a self, iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        let cont_name = &self.cont_name;

        let all_gen_use = &self.generics.gen_use;

        for TraitInfo {
            vtbl_name,
            path,
            vtbl_typename,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in iter
        {
            ret.extend(
                quote!(#vtbl_name: &'cglue_a #path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #all_gen_use>, #gen_use>, ),
            );
        }

        ret
    }

    /// Get a sequence of `Trait1 + Trait2 + Trait3 ...`
    ///
    /// # Arguments
    ///
    /// * `traits` - traits to combine.
    fn impl_traits<'a>(&'a self, traits: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        for (
            i,
            TraitInfo {
                path,
                ident,
                generics:
                    ParsedGenerics {
                        life_use, gen_use, ..
                    },
                ..
            },
        ) in traits.enumerate()
        {
            if i != 0 {
                ret.extend(quote!(+));
            }

            let (hrtb, life_use) = if life_use.is_empty() {
                (quote!(), quote!())
            } else {
                (quote!(for<'cglue_c>), quote!('cglue_c,))
            };

            ret.extend(quote!(#hrtb #path #ident <#life_use #gen_use>));
        }

        ret
    }

    /// Optional and vtable definitions.
    ///
    /// Optional means they are of type `Option<&'cglue_a VTable>`.
    fn optional_vtbl_defs(&self, inst_ident: TokenStream, ctx_ident: TokenStream) -> TokenStream {
        let mut ret = TokenStream::new();

        let cont_name = &self.cont_name;

        let gen_all_use = &self.generics.gen_use;

        for TraitInfo {
            vtbl_name,
            path,
            vtbl_typename,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in &self.optional_vtbl
        {
            ret.extend(
                quote!(#vtbl_name: ::core::option::Option<&'cglue_a #path #vtbl_typename<'cglue_a, #cont_name<#inst_ident, #ctx_ident, #gen_all_use>, #gen_use>>, ),
            );
        }

        ret
    }

    fn ret_tmp_defs<'a>(&'a self, iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo {
            ret_tmp_name,
            path,
            ret_tmp_typename,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in self.mandatory_vtbl.iter().chain(iter)
        {
            ret.extend(quote!(#ret_tmp_name: #path #ret_tmp_typename<CGlueCtx, #gen_use>, ));
        }

        ret
    }

    /// Mixed vtable definitoins.
    ///
    /// This function goes through optional vtables, and mixes them between `Option`, and
    /// non-`Option` types for the definitions.
    ///
    /// # Arguments
    ///
    /// * `iter` - iterator of required/mandatory types. These types will have non-`Option` type
    /// assigned. It is crucial to have the same order of values!
    fn mixed_opt_vtbl_defs<'a>(&'a self, iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        let mut iter = iter.peekable();

        let cont_name = &self.cont_name;

        let all_gen_use = &self.generics.gen_use;

        for (
            TraitInfo {
                vtbl_name,
                path,
                vtbl_typename,
                generics: ParsedGenerics { gen_use, .. },
                ..
            },
            mandatory,
        ) in self.optional_vtbl.iter().map(|v| {
            if iter.peek() == Some(&v) {
                iter.next();
                (v, true)
            } else {
                (v, false)
            }
        }) {
            let def = match mandatory {
                true => {
                    quote!(#vtbl_name: &'cglue_a #path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #all_gen_use>, #gen_use>, )
                }
                false => {
                    quote!(#vtbl_name: ::core::option::Option<&'cglue_a #path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #all_gen_use>, #gen_use>>, )
                }
            };
            ret.extend(def);
        }

        ret
    }

    /// Generate a `GetContainer` implementation for a specific cglue object.
    fn get_container_impl(
        &self,
        name: &Ident,
        trg_path: &TokenStream,
        all_generics: &ParsedGenerics,
    ) -> TokenStream {
        let cont_name = &self.cont_name;

        let ParsedGenerics {
            gen_declare,
            gen_use,
            gen_where_bounds,
            ..
        } = &all_generics;

        let ctx_bound = super::traits::ctx_bound();

        quote! {
            impl<CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #gen_declare>
                #trg_path::GetContainer for #name<'_, CGlueInst, CGlueCtx, #gen_use>
            where
                #cont_name<CGlueInst, CGlueCtx, #gen_use>: #trg_path::CGlueObjBase,
                #gen_where_bounds
            {
                type ContType = #cont_name<CGlueInst, CGlueCtx, #gen_use>;

                fn ccont_ref(&self) -> &Self::ContType {
                    &self.container
                }

                fn ccont_mut(&mut self) -> &mut Self::ContType {
                    &mut self.container
                }

                fn into_ccont(self) -> Self::ContType {
                    self.container
                }

                fn build_with_ccont(&self, container: Self::ContType) -> Self {
                    Self {
                        container,
                        ..*self
                    }
                }
            }
        }
    }

    fn cglue_obj_impl(&self, trg_path: &TokenStream, all_generics: &ParsedGenerics) -> TokenStream {
        let cont_name = &self.cont_name;

        let ParsedGenerics {
            gen_declare: all_gen_declare,
            gen_use: all_gen_use,
            gen_where_bounds: all_gen_where_bounds,
            ..
        } = &all_generics;

        let ctx_bound = super::traits::ctx_bound();

        let mut ret = quote! {
            impl<CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #all_gen_declare> #trg_path::CGlueObjBase
                for #cont_name<CGlueInst, CGlueCtx, #all_gen_use>
            where
                CGlueInst::Target: Sized,
                #all_gen_where_bounds
            {
                type ObjType = CGlueInst::Target;
                type InstType = CGlueInst;
                type Context = CGlueCtx;

                fn cobj_base_ref(&self) -> (&Self::ObjType, &Self::Context) {
                    (self.instance.deref(), &self.context)
                }

                fn cobj_base_owned(self) -> (Self::InstType, Self::Context) {
                    (self.instance, self.context)
                }
            }
        };

        for TraitInfo {
            path,
            ret_tmp_typename,
            ret_tmp_name,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in self.mandatory_vtbl.iter().chain(self.optional_vtbl.iter())
        {
            ret.extend(quote!{
                impl<CGlueInst: ::core::ops::Deref, CGlueCtx: #ctx_bound, #all_gen_declare>
                    #trg_path::CGlueObjRef<#path #ret_tmp_typename<CGlueCtx, #gen_use>>
                    for #cont_name<CGlueInst, CGlueCtx, #all_gen_use>
                where
                    CGlueInst::Target: Sized,
                    #all_gen_where_bounds
                {
                    fn cobj_ref(&self) -> (&Self::ObjType, &#path #ret_tmp_typename<CGlueCtx, #gen_use>, &Self::Context) {
                        (self.instance.deref(), &self.#ret_tmp_name, &self.context)
                    }
                }

                impl<
                        CGlueInst: ::core::ops::DerefMut,
                        CGlueCtx: #ctx_bound,
                        #all_gen_declare
                    > #trg_path::CGlueObjMut<#path #ret_tmp_typename<CGlueCtx, #gen_use>>
                    for #cont_name<CGlueInst, CGlueCtx, #all_gen_use>
                where
                    CGlueInst::Target: Sized,
                    #all_gen_where_bounds
                {
                    fn cobj_mut(&mut self) -> (&mut Self::ObjType, &mut #path #ret_tmp_typename<CGlueCtx, #gen_use>, &Self::Context) {
                        (
                            self.instance.deref_mut(),
                            &mut self.#ret_tmp_name,
                            &self.context,
                        )
                    }
                }
            });
        }

        ret
    }

    /// `GetVtbl<Vtable>`, `CGlueObjRef<RetTmp>`, `CGlueObjOwned<RetTmp>`, `CGlueObjBuild<RetTmp>`, and `CGlueObjMut<T, RetTmp>` implementations for mandatory vtables.
    fn mandatory_as_ref_impls(&self, trg_path: &TokenStream) -> TokenStream {
        self.as_ref_impls(
            &self.name,
            self.mandatory_vtbl.iter(),
            &self.generics,
            trg_path,
        )
    }

    /// `GetVtbl<Vtable>`, `CGlueObjRef<RetTmp>`, `CGlueObjOwned<RetTmp>`, `CGlueObjBuild<RetTmp>`, and `CGlueObjMut<T, RetTmp>` implementations for arbitrary type and list of tables.
    ///
    /// # Arguments
    ///
    /// * `name` - type name to implement the conversion for.
    /// * `traits` - vtable types to implement the conversion to.
    fn as_ref_impls<'a>(
        &'a self,
        name: &Ident,
        traits: impl Iterator<Item = &'a TraitInfo>,
        all_generics: &ParsedGenerics,
        trg_path: &TokenStream,
    ) -> TokenStream {
        let mut ret = TokenStream::new();

        let cont_name = &self.cont_name;

        let all_gen_declare = &all_generics.gen_declare;
        let all_gen_use = &all_generics.gen_use;
        let all_gen_where_bounds = &all_generics.gen_where_bounds;

        let ctx_bound = super::traits::ctx_bound();

        for TraitInfo {
            vtbl_name,
            path,
            vtbl_typename,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in traits
        {
            ret.extend(quote! {

                // TODO: bring back CGlueObjBuild

                impl<'cglue_a, CGlueInst, CGlueCtx: #ctx_bound, #all_gen_declare> #trg_path::GetVtbl<#path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #all_gen_use>, #gen_use>>
                    for #name<'cglue_a, CGlueInst, CGlueCtx, #all_gen_use>
                where
                    #cont_name<CGlueInst, CGlueCtx, #all_gen_use>: #trg_path::CGlueObjBase,
                    #all_gen_where_bounds
                {
                    fn get_vtbl(&self) -> &#path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #all_gen_use>, #gen_use> {
                        &self.#vtbl_name
                    }
                }
            });
        }

        ret
    }

    /// List of `vtbl: Default::default(), ` for all mandatory vtables.
    fn mandatory_vtbl_defaults(&self) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo { vtbl_name, .. } in &self.mandatory_vtbl {
            ret.extend(quote!(#vtbl_name: Default::default(),));
        }

        ret
    }

    fn mandatory_ret_tmp_defaults(&self) -> TokenStream {
        Self::ret_tmp_defaults(self.mandatory_vtbl.iter())
    }

    fn ret_tmp_defaults<'a>(iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo { ret_tmp_name, .. } in iter {
            ret.extend(quote!(#ret_tmp_name: Default::default(),));
        }

        ret
    }

    /// List of `vtbl: None, ` for all optional vtables.
    #[cfg_attr(not(feature = "unstable"), allow(unused))]
    fn default_opt_vtbl_list(&self) -> TokenStream {
        let mut ret = TokenStream::new();

        #[cfg(feature = "unstable")]
        let crate_path = crate::util::crate_path();

        let cont_name = &self.cont_name;

        let gen_all_use = &self.generics.gen_use;

        for TraitInfo {
            vtbl_name,
            path,
            vtbl_typename,
            generics: ParsedGenerics { gen_use, .. },
            ..
        } in &self.optional_vtbl
        {
            #[cfg(feature = "unstable")]
            {
                let vtbl_ty = quote!(&'cglue_a #path #vtbl_typename<'cglue_a, #cont_name<CGlueInst, CGlueCtx, #gen_all_use>, #gen_use>);
                ret.extend(quote!(#vtbl_name: <#vtbl_ty as #crate_path::TryDefault<#vtbl_ty>>::try_default(),));
            }
            #[cfg(not(feature = "unstable"))]
            ret.extend(quote!(#vtbl_name: None,));
        }

        ret
    }

    /// Simple identifier list.
    fn vtbl_list<'a>(&'a self, iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo { vtbl_name, .. } in iter {
            ret.extend(quote!(#vtbl_name,));
        }

        ret
    }

    /// Try-unwrapping assignment list `vtbl: vtbl?, `.
    ///
    /// # Arguments
    ///
    /// * `iter` - vtable identifiers to list and try-unwrap.
    fn vtbl_unwrap_list<'a>(&'a self, iter: impl Iterator<Item = &'a TraitInfo>) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo { vtbl_name, .. } in iter {
            ret.extend(quote!(#vtbl_name: #vtbl_name?,));
        }

        ret
    }

    /// Mixed try-unwrap list for vtables.
    ///
    /// This function goes through optional vtables, unwraps the ones in `iter`, leaves others
    /// bare.
    ///
    /// # Arguments
    ///
    /// * `iter` - list of vtables to try-unwrap. Must be ordered the same way!
    fn mixed_opt_vtbl_unwrap_list<'a>(
        &'a self,
        iter: impl Iterator<Item = &'a TraitInfo>,
    ) -> TokenStream {
        let mut ret = TokenStream::new();

        let mut iter = iter.peekable();

        for (TraitInfo { vtbl_name, .. }, mandatory) in self.optional_vtbl.iter().map(|v| {
            if iter.peek() == Some(&v) {
                iter.next();
                (v, true)
            } else {
                (v, false)
            }
        }) {
            let def = match mandatory {
                true => quote!(#vtbl_name: #vtbl_name?, ),
                false => quote!(#vtbl_name, ),
            };
            ret.extend(def);
        }

        ret
    }

    /// Try-unwrap a list of vtables without assigning them (`vtbl?,`).
    ///
    /// # Arguments
    ///
    /// * `iter` - vtables to unwrap.
    fn vtbl_unwrap_validate<'a>(
        &'a self,
        iter: impl Iterator<Item = &'a TraitInfo>,
    ) -> TokenStream {
        let mut ret = TokenStream::new();

        for TraitInfo { vtbl_name, .. } in iter {
            ret.extend(quote!((*#vtbl_name)?,));
        }

        ret
    }

    /// Bind `Default` to mandatory vtables.
    pub fn vtbl_where_bounds<'a>(
        iter: impl Iterator<Item = &'a TraitInfo>,
        cont_name: &Ident,
        container_ident: TokenStream,
        ctx_ident: TokenStream,
        all_generics: &ParsedGenerics,
        trait_bound: Option<&TokenStream>,
        vtbl_lifetime: &Lifetime,
    ) -> TokenStream {
        let mut ret = TokenStream::new();

        let all_gen_use = &all_generics.gen_use;

        for TraitInfo {
            path,
            ident,
            vtbl_typename,
            generics: ParsedGenerics {
                gen_use, life_use, ..
            },
            ..
        } in iter
        {
            // FIXME: this is a bit of a hack. 0.1 could do multiple generic implementations
            // without trait bounds just fine.
            if let Some(trait_bound) = &trait_bound {
                // FIXME: this will not work with multiple lifetimes.
                let life_use = if life_use.is_empty() {
                    None
                } else {
                    Some(quote!('cglue_a,))
                };

                ret.extend(quote!(#trait_bound: #path #ident<#life_use #gen_use>,));
            }

            ret.extend(quote!(&#vtbl_lifetime #path #vtbl_typename<#vtbl_lifetime, #cont_name<#container_ident, #ctx_ident, #all_gen_use>, #gen_use>: #vtbl_lifetime + Default,));
        }

        ret
    }
}