about summary refs log tree commit diff stats
path: root/wrapperhelper/src/generator.c
blob: 42eeb904138172a056603ffc4b15c3e2b631d5fa (plain) (blame)
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
#include "generator.h"

#include "lang.h"
#include "log.h"
#include "prepare.h"

static const char *rft2str[8] = {
	[RQT_FUN] = "",
	[RQT_FUN_2] = "",
	[RQT_FUN_MY] = " (my)",
	[RQT_FUN_D] = " (D)",
	[RQT_DATA] = "",
	[RQT_DATAB] = " (B)",
	[RQT_DATAM] = " (my)",
};
#define IS_RQT_FUN2(rty) (((rty) == RQT_FUN_2) || ((rty) == RQT_FUN_D))
#define IS_RQT_FUNCTION(rty) ((rty) < RQT_DATA)

void request_print(const request_t *req) {
	printf("%s%s: %sdefault", string_content(req->obj_name), req->weak ? " (weak)" : "", req->default_comment ? "commented " : "");
	switch (req->def.rty) {
	case RQT_FUN:
	case RQT_FUN_2:
	case RQT_FUN_MY:
	case RQT_FUN_D:
		if (req->def.fun.typ) {
			printf(" function%s%s %s%s%s",
				rft2str[req->def.rty],
				req->def.fun.needs_S ? " (with S)" : "",
				string_content(req->def.fun.typ),
				req->def.fun.fun2 ? " -> " : "",
				req->def.fun.fun2 ? string_content(req->def.fun.fun2) : "");
		} else {
			printf(" untyped function%s%s", rft2str[req->def.rty], req->def.fun.needs_S ? " (with S)" : "");
		}
		break;
	case RQT_DATA:
	case RQT_DATAB:
	case RQT_DATAM:
		if (req->def.dat.has_size) {
			printf(" data%s %zu", rft2str[req->def.rty], req->def.dat.sz);
		} else {
			printf(" unsized data%s", rft2str[req->def.rty]);
		}
		break;
	}
	if (req->has_val) {
		printf(" => solved");
		switch (req->val.rty) {
		case RQT_FUN:
		case RQT_FUN_2:
		case RQT_FUN_MY:
		case RQT_FUN_D:
			if (req->val.fun.typ) {
				printf(" function%s%s %s%s%s",
					rft2str[req->val.rty],
					req->val.fun.needs_S ? " (with S)" : "",
					string_content(req->val.fun.typ),
					req->val.fun.fun2 ? " -> " : "",
					req->val.fun.fun2 ? string_content(req->val.fun.fun2) : "");
			} else {
				printf(" untyped function%s%s", rft2str[req->val.rty], req->val.fun.needs_S ? " (with S)" : "");
			}
			break;
		case RQT_DATA:
		case RQT_DATAB:
		case RQT_DATAM:
			if (req->val.dat.has_size) {
				printf(" data%s %zu", rft2str[req->val.rty], req->val.dat.sz);
			} else {
				printf(" unsized data%s", rft2str[req->val.rty]);
			}
			break;
		}
	}
	printf("\n");
}
void request_print_check(const request_t *req) {
	if (req->ignored) {
		return;
	}
	if (!req->has_val) {
		// printf("%s: no value\n", string_content(req->obj_name));
		return;
	}
	if ((IS_RQT_FUNCTION(req->def.rty) != IS_RQT_FUNCTION(req->val.rty))) {
		printf("%s: conflict: %s data, %s function\n",
			string_content(req->obj_name),
			IS_RQT_FUNCTION(req->def.rty) ? "is" : "was",
			IS_RQT_FUNCTION(req->def.rty) ? "was" : "is");
		return;
	}
	if (IS_RQT_FUNCTION(req->def.rty) && !req->def.fun.typ) return;       // No default (function)
	if (!IS_RQT_FUNCTION(req->def.rty) && !req->def.dat.has_size) return; // No default (data)
	// We have a default and a value, both are functions or data
	int similar;
	switch (req->def.rty) {
	case RQT_FUN:
	case RQT_FUN_2:
	case RQT_FUN_MY:
	case RQT_FUN_D:
		similar = !req->default_comment || (req->val.rty != RQT_FUN); // From comment to no comment is dissimilar
		if (similar && (req->def.rty != req->val.rty)) similar = 0;
		if (similar && strcmp(string_content(req->def.fun.typ), string_content(req->val.fun.typ))) {
			// "//GOM(_, .F...)" == "//GOM(_, .FE...)"
			similar = req->default_comment
			       && (req->def.rty == RQT_FUN_MY)
			       && !strncmp(string_content(req->def.fun.typ), string_content(req->val.fun.typ), 2)
			       && (string_content(req->val.fun.typ)[2] == 'E')
			       && !strcmp(string_content(req->def.fun.typ) + 2, string_content(req->val.fun.typ) + 3);
		}
		if (!similar) {
			printf("%s%s: function with %s%sdefault%s%s%s%s%s%s and dissimilar %ssolved%s%s%s%s%s%s\n",
				string_content(req->obj_name),
				req->weak ? " (weak)" : "",
				req->default_comment ? "commented " : "",
				req->def.fun.typ ? "" : "untyped ",
				rft2str[req->def.rty],
				req->def.fun.needs_S ? " (with S)" : "",
				req->def.fun.typ ? " " : "",
				string_content(req->def.fun.typ),
				req->def.fun.fun2 ? " -> " : "",
				req->def.fun.fun2 ? string_content(req->def.fun.fun2) : "",
				req->val.fun.typ ? "" : "untyped ",
				rft2str[req->val.rty],
				req->val.fun.needs_S ? " (with S)" : "",
				req->val.fun.typ ? " " : "",
				string_content(req->val.fun.typ),
				req->val.fun.fun2 ? " -> " : "",
				req->val.fun.fun2 ? string_content(req->val.fun.fun2) : "");
		}
		break;
	case RQT_DATA:
	case RQT_DATAB:
	case RQT_DATAM:
		similar = 1;
		if (similar && (req->def.rty != req->val.rty)) similar = 0;
		if (similar && (!!req->def.dat.has_size != !!req->val.dat.has_size)) similar = 0;
		if (similar && req->def.dat.has_size && (req->def.dat.sz != req->val.dat.sz)) similar = 0;
		if (!similar) {
			printf("%s%s: data with %s%sdefault%s",
				string_content(req->obj_name),
				req->weak ? " (weak)" : "",
				req->default_comment ? "commented " : "",
				req->def.fun.typ ? "" : "untyped ",
				rft2str[req->def.rty]);
			if (req->def.dat.has_size) {
				printf(" %zu", req->def.dat.sz);
			} else {
				printf(" unsized");
			}
			printf(" and dissimilar %ssolved%s",
				req->val.fun.typ ? "" : "untyped ",
				rft2str[req->val.rty]);
			if (req->val.dat.has_size) {
				printf(" %zu", req->val.dat.sz);
			} else {
				printf(" unsized");
			}
			printf("\n");
		}
		break;
	}
}
void references_print_check(const VECTOR(references) *refs) {
	vector_for(references, ref, refs) {
		if (ref->typ == REF_REQ) request_print_check(&ref->req);
	}
}

static void request_del(request_t *req) {
	string_del(req->obj_name);
	switch (req->def.rty) {
	case RQT_FUN:    if (req->def.fun.typ) string_del(req->def.fun.typ);                                                       break;
	case RQT_FUN_2:  if (req->def.fun.typ) string_del(req->def.fun.typ); if (req->def.fun.fun2) string_del(req->def.fun.fun2); break;
	case RQT_FUN_MY: if (req->def.fun.typ) string_del(req->def.fun.typ);                                                       break;
	case RQT_FUN_D:  if (req->def.fun.typ) string_del(req->def.fun.typ); if (req->def.fun.fun2) string_del(req->def.fun.fun2); break;
	case RQT_DATA:   break;
	case RQT_DATAB:  break;
	case RQT_DATAM:  break;
	}
	if (req->has_val) {
		switch (req->val.rty) {
		case RQT_FUN:    string_del(req->val.fun.typ);                                break;
		case RQT_FUN_2:  string_del(req->val.fun.typ); string_del(req->val.fun.fun2); break;
		case RQT_FUN_MY: string_del(req->val.fun.typ);                                break;
		case RQT_FUN_D:  string_del(req->val.fun.typ); string_del(req->val.fun.fun2); break;
		case RQT_DATA:   break;
		case RQT_DATAB:  break;
		case RQT_DATAM:  break;
		}
	}
}
static void reference_del(reference_t *ref) {
	switch (ref->typ) {
	case REF_REQ:
		request_del(&ref->req);
		break;
	case REF_LINE:
	case REF_IFDEF:
	case REF_IFNDEF:
		string_del(ref->line);
		break;
	case REF_ELSE:
	case REF_ENDIF:
		break;
	}
}

static int valid_reqtype(string_t *t) {
	const char *s = string_content(t);
	if (!((s[0] >= 'A') && (s[0] <= 'Z')) && !((s[0] >= 'a') && (s[0] <= 'z'))) return 0;
	if (s[1] != 'F') return 0;
	for (size_t i = 2; i < string_len(t); ++i) {
		if (!((s[i] >= 'A') && (s[i] <= 'Z')) && !((s[i] >= 'a') && (s[i] <= 'z'))) return 0;
	}
	return 1;
}
static const char *rqt_suffix[8] = {
	[RQT_FUN] = "",
	[RQT_FUN_2] = "2",
	[RQT_FUN_MY] = "M",
	[RQT_FUN_D] = "D",
	[RQT_DATA] = "",
	[RQT_DATAB] = "B",
	[RQT_DATAM] = "M",
};

static void request_output(FILE *f, const request_t *req) {
	if (!req->has_val) {
		if (IS_RQT_FUNCTION(req->def.rty)) {
			if (!req->def.fun.typ) {
				fprintf(f, "//GO%s%s%s(%s, \n",
					req->weak ? "W" : "",
					req->def.fun.needs_S ? "S" : "",
					rqt_suffix[req->def.rty],
					string_content(req->obj_name));
			} else {
				fprintf(f, "%sGO%s%s%s(%s, %s%s%s%s%s)%s\n",
					req->default_comment ? "//" : "",
					req->weak ? "W" : "",
					req->def.fun.needs_S ? "S" : "",
					rqt_suffix[req->def.rty],
					string_content(req->obj_name),
					valid_reqtype(req->def.fun.typ) ? "" : "\"",
					string_content(req->def.fun.typ),
					valid_reqtype(req->def.fun.typ) ? "" : "\"",
					IS_RQT_FUN2(req->def.rty) ? ", " : "",
					IS_RQT_FUN2(req->def.rty) ? string_content(req->def.fun.fun2) : "",
					(req->ignored || req->default_comment) ? "" : " // Warning: failed to confirm");
			}
		} else {
			if (req->def.dat.has_size) {
				fprintf(f, "%sDATA%s%s(%s, %zu)%s\n",
					req->default_comment ? "//" : "",
					req->weak ? "V" : "",
					rqt_suffix[req->def.rty],
					string_content(req->obj_name),
					req->def.dat.sz,
					(req->ignored || req->default_comment) ? "" : " // Warning: failed to confirm");
			} else {
				fprintf(f, "//DATA%s%s(%s, \n",
					req->weak ? "V" : "",
					rqt_suffix[req->def.rty],
					string_content(req->obj_name));
			}
		}
	} else {
		if (IS_RQT_FUNCTION(req->val.rty)) {
			int is_comment =
				(IS_RQT_FUNCTION(req->def.rty) && req->def.fun.typ && !req->default_comment)
				  ? (req->val.rty != req->def.rty) : (req->val.rty != RQT_FUN);
			fprintf(f, "%sGO%s%s%s(%s, %s%s%s)\n",
				is_comment ? "//" : "",
				req->weak ? "W" : "",
				req->val.fun.needs_S ? "S" : "",
				rqt_suffix[req->val.rty],
				string_content(req->obj_name),
				string_content(req->val.fun.typ),
				IS_RQT_FUN2(req->val.rty) ? ", " : "",
				IS_RQT_FUN2(req->val.rty) ? req->val.fun.fun2 ? string_content(req->val.fun.fun2) : "<error: no val>" : "");
		} else {
			if (req->val.dat.has_size) {
				int is_comment = IS_RQT_FUNCTION(req->def.rty) || !req->def.dat.has_size || req->default_comment || (req->def.rty != req->val.rty);
				fprintf(f, "%sDATA%s%s(%s, %zu)\n",
					is_comment ? "//" : "",
					req->weak ? "V" : "",
					rqt_suffix[req->val.rty],
					string_content(req->obj_name),
					req->val.dat.sz);
			} else {
				fprintf(f, "//DATA%s%s(%s, \n",
					req->weak ? "V" : "",
					rqt_suffix[req->val.rty],
					string_content(req->obj_name));
			}
		}
	}
}
static void reference_output(FILE *f, const reference_t *ref) {
	switch (ref->typ) {
	case REF_REQ:
		request_output(f, &ref->req);
		break;
	case REF_LINE:
		fputs(string_content(ref->line), f);
		fputc('\n', f);
		break;
	case REF_IFDEF:
		fprintf(f, "#ifdef %s\n", string_content(ref->line));
		break;
	case REF_IFNDEF:
		fprintf(f, "#ifndef %s\n", string_content(ref->line));
		break;
	case REF_ELSE:
		fputs("#else\n", f);
		break;
	case REF_ENDIF:
		fputs("#endif\n", f);
		break;
	}
}
void output_from_references(FILE *f, const VECTOR(references) *refs) {
	fprintf(f, "#if !(defined(GO) && defined(GOM) && defined(GO2) && defined(DATA))\n#error Meh...\n#endif\n");
	vector_for(references, ref, refs) {
		reference_output(f, ref);
	}
}

VECTOR_IMPL(references, reference_del)

VECTOR(references) *references_from_file(const char *filename, FILE *f) {
	prepare_t *prep = prepare_new_file(f, filename);
	if (!prep) {
		log_memory("failed to create the prepare structure for the reference file\n");
		return NULL;
	}
	
	VECTOR(references) *ret = vector_new(references);
	if (!ret) {
		log_memory("failed to create a new reference vector\n");
		prepare_del(prep);
		return NULL;
	}
	
	int lineno = 1;
	
	// Ignore the first 3 lines
	preproc_token_t tok;
	do {
		tok = pre_next_token(prep, 0);
		if (tok.tokt == PPTOK_NEWLINE) ++lineno;
		else preproc_token_del(&tok); // NEWLINE has no destructor
	} while (!preproc_token_isend(&tok) && (lineno < 4));
	
	// TODO: better conditionals handling
	// Also, for now assume we have no definition
	int if_depth = 0, entered_depth = 0;
	string_t *line = string_new();
	if (!line) {
		log_memory("failed to allocate new string for new reference line\n");
	}
	
#define ADD_CHAR(c, has_destr, what) \
		if (!string_add_char(line, c)) {            \
			log_memory("failed to add " what "\n"); \
			if (has_destr) preproc_token_del(&tok); \
			goto failed;                            \
		}
#define ADD_CSTR(cstr, has_destr, what) \
		if (!string_add_cstr(line, cstr)) {         \
			log_memory("failed to add " what "\n"); \
			if (has_destr) preproc_token_del(&tok); \
			goto failed;                            \
		}
#define ADD_STR(str, has_destr, what) \
		if (!string_add_string(line, str)) {        \
			log_memory("failed to add " what "\n"); \
			if (has_destr) preproc_token_del(&tok); \
			goto failed;                            \
		}
#define PUSH_LINE(has_destr) \
		string_trim(line);                                                                   \
		if (!vector_push(references, ret, ((reference_t){.typ = REF_LINE, .line = line}))) { \
			log_memory("failed to memorize reference line %d\n", lineno);                    \
			if (has_destr) preproc_token_del(&tok);                                          \
			goto failed;                                                                     \
		}                                                                                    \
		line = string_new();                                                                 \
		if (!line) {                                                                         \
			log_memory("failed to allocate new string for new reference line\n");            \
		}
	
	while (1) {
		int is_comment = 0;
		tok = pre_next_token(prep, 1);
		if (tok.tokt == PPTOK_START_LINE_COMMENT) {
			ADD_CSTR("//", 0, "start of comment")
			is_comment = 1;
			// Empty destructor
			tok = pre_next_token(prep, 0); // tok is IDENT, NEWLINE, INVALID or BLANK
			while ((tok.tokt == PPTOK_BLANK) && ((tok.tokv.c == ' ') || (tok.tokv.c == '\t'))) {
				ADD_CHAR(tok.tokv.c, 0, "start of comment")
				// Empty destructor
				tok = pre_next_token(prep, 0); // tok is IDENT, NEWLINE, INVALID or BLANK
			}
		}
		if ((tok.tokt == PPTOK_SYM) && (tok.tokv.sym == SYM_HASH)) {
			string_clear(line);
			tok = pre_next_token(prep, 0);
			if (tok.tokt != PPTOK_IDENT) {
				log_error(&tok.loginfo, "invalid reference file: invalid preprocessor line\n");
				preproc_token_del(&tok);
				goto failed;
			}
			if (!strcmp(string_content(tok.tokv.str), "ifdef")) {
				string_del(tok.tokv.str);
				tok = pre_next_token(prep, 0);
				if (tok.tokt != PPTOK_IDENT) {
					log_error(&tok.loginfo, "invalid reference file: invalid '#ifdef' line\n");
					preproc_token_del(&tok);
					goto failed;
				}
				++if_depth;
				if (!vector_push(references, ret, ((reference_t){.typ = REF_IFDEF, .line = tok.tokv.str}))) {
					log_error(&tok.loginfo, "failed to memorize reference line %d\n", lineno);
					string_del(tok.tokv.str);
					goto failed;
				}
				tok = pre_next_token(prep, 0);
			} else if (!strcmp(string_content(tok.tokv.str), "ifndef")) {
				string_del(tok.tokv.str);
				tok = pre_next_token(prep, 0);
				if (tok.tokt != PPTOK_IDENT) {
					log_error(&tok.loginfo, "invalid reference file: invalid '#ifndef' line\n");
					preproc_token_del(&tok);
					goto failed;
				}
				if (if_depth == entered_depth) ++entered_depth;
				++if_depth;
				if (!vector_push(references, ret, ((reference_t){.typ = REF_IFNDEF, .line = tok.tokv.str}))) {
					log_error(&tok.loginfo, "failed to memorize reference line %d\n", lineno);
					string_del(tok.tokv.str);
					goto failed;
				}
				tok = pre_next_token(prep, 0);
			} else if (!strcmp(string_content(tok.tokv.str), "else")) {
				string_del(tok.tokv.str);
				tok = pre_next_token(prep, 0);
				if (if_depth == entered_depth + 1) ++entered_depth;
				else if (if_depth == entered_depth) --entered_depth;
				if (!vector_push(references, ret, ((reference_t){.typ = REF_ELSE}))) {
					log_error(&tok.loginfo, "failed to memorize reference line %d\n", lineno);
					goto failed;
				}
			} else if (!strcmp(string_content(tok.tokv.str), "endif")) {
				string_del(tok.tokv.str);
				tok = pre_next_token(prep, 0);
				if (if_depth == entered_depth) --entered_depth;
				--if_depth;
				if (!vector_push(references, ret, ((reference_t){.typ = REF_ENDIF}))) {
					log_error(&tok.loginfo, "failed to memorize reference line %d\n", lineno);
					goto failed;
				}
			} else {
				log_error(&tok.loginfo, "invalid reference file: invalid preprocessor command '%s'\n", string_content(tok.tokv.str));
				string_del(tok.tokv.str);
				goto failed;
			}
			while (!preproc_token_isend(&tok) && (tok.tokt != PPTOK_NEWLINE)) {
				preproc_token_del(&tok);
				tok = pre_next_token(prep, 0);
			}
			++lineno;
			if (preproc_token_isend(&tok)) {
				if (tok.tokt == PPTOK_EOF) goto success;
				else {
					preproc_token_del(&tok);
					goto failed;
				}
			}
		} else if (tok.tokt == PPTOK_NEWLINE) {
			PUSH_LINE(0)
			++lineno;
		} else if (tok.tokt == PPTOK_EOF) {
			goto success;
		} else if ((tok.tokt == PPTOK_IDENT)
		        && (!strcmp(string_content(tok.tokv.str), "GO")
		         || !strcmp(string_content(tok.tokv.str), "GO2")
		         || !strcmp(string_content(tok.tokv.str), "GOD")
		         || !strcmp(string_content(tok.tokv.str), "GOM")
		         || !strcmp(string_content(tok.tokv.str), "GOS")
		         || !strcmp(string_content(tok.tokv.str), "GOW")
		         || !strcmp(string_content(tok.tokv.str), "GOW2")
		         || !strcmp(string_content(tok.tokv.str), "GOWD")
		         || !strcmp(string_content(tok.tokv.str), "GOWM")
		         || !strcmp(string_content(tok.tokv.str), "GOWS"))) {
			string_clear(line);
			if (is_comment) prepare_mark_nocomment(prep);
			int isweak = (string_content(tok.tokv.str)[2] == 'W');
			request_t req = {
				.default_comment = is_comment,
				.has_val = 0,
				.ignored = 0,
				.obj_name = NULL,
				.weak = isweak,
				.def = {
					.rty =
						(string_content(tok.tokv.str)[isweak ? 3 : 2] == '2') ? RQT_FUN_2 :
						(string_content(tok.tokv.str)[isweak ? 3 : 2] == 'D') ? RQT_FUN_D :
						(string_content(tok.tokv.str)[isweak ? 3 : 2] == 'M') ? RQT_FUN_MY : RQT_FUN,
					.fun.needs_S = (string_content(tok.tokv.str)[isweak ? 3 : 2] == 'S'),
					.fun.typ = NULL,
					.fun.fun2 = NULL,
				},
				.val = {0},
			};
			string_del(tok.tokv.str);
			tok = pre_next_token(prep, 0);
			if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_LPAREN)) {
				log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (lparen)\n", lineno);
				preproc_token_del(&tok);
				goto failed;
			}
			// Empty destructor
			tok = pre_next_token(prep, 0);
			if (tok.tokt != PPTOK_IDENT) {
				log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (obj_name)\n", lineno);
				preproc_token_del(&tok);
				goto failed;
			}
			req.obj_name = tok.tokv.str;
			// Token moved
			tok = pre_next_token(prep, 0);
			if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_COMMA)) {
				log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (comma)\n", lineno);
				string_del(req.obj_name);
				preproc_token_del(&tok);
				goto failed;
			}
			// Empty destructor
			tok = pre_next_token(prep, 0);
			if ((tok.tokt == PPTOK_IDENT) || (tok.tokt == PPTOK_STRING)) {
				req.def.fun.typ = (tok.tokt == PPTOK_STRING) ? tok.tokv.sstr : tok.tokv.str;
				// Token moved
				tok = pre_next_token(prep, 0);
				if ((req.def.rty == RQT_FUN_2) || (req.def.rty == RQT_FUN_D)) {
					if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_COMMA)) {
						log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (comma 2)\n", lineno);
						string_del(req.obj_name);
						string_del(req.def.fun.typ);
						preproc_token_del(&tok);
						goto failed;
					}
					// Empty destructor
					tok = pre_next_token(prep, 0);
					if (tok.tokt != PPTOK_IDENT) {
						log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (redirect)\n", lineno);
						string_del(req.obj_name);
						string_del(req.def.fun.typ);
						preproc_token_del(&tok);
						goto failed;
					}
					req.def.fun.fun2 = tok.tokv.str;
					// Token moved
					tok = pre_next_token(prep, 0);
				}
				if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_RPAREN)) {
					log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (rparen)\n", lineno);
					string_del(req.obj_name);
					string_del(req.def.fun.typ);
					if (req.def.fun.fun2) string_del(req.def.fun.fun2);
					preproc_token_del(&tok);
					goto failed;
				}
				// Empty destructor
				tok = pre_next_token(prep, 0);
			}
			if (tok.tokt != PPTOK_NEWLINE) {
				log_error(&tok.loginfo, "invalid reference file: invalid GO line %d (newline)\n", lineno);
				string_del(req.obj_name);
				if (req.def.fun.typ) string_del(req.def.fun.typ);
				if (req.def.fun.fun2) string_del(req.def.fun.fun2);
				preproc_token_del(&tok);
				goto failed;
			}
			if (!vector_push(references, ret, ((reference_t){.typ = REF_REQ, .req = req}))) {
				log_memory("failed to add reference for %s\n", string_content(req.obj_name));
				string_del(req.obj_name);
				if (req.def.fun.typ) string_del(req.def.fun.typ);
				if (req.def.fun.fun2) string_del(req.def.fun.fun2);
				// Empty destructor
				goto failed;
			}
			++lineno;
		} else if ((tok.tokt == PPTOK_IDENT)
		        && (!strcmp(string_content(tok.tokv.str), "DATA")
		         || !strcmp(string_content(tok.tokv.str), "DATAV")
		         || !strcmp(string_content(tok.tokv.str), "DATAB")
		         || !strcmp(string_content(tok.tokv.str), "DATAM"))) {
			string_clear(line);
			if (is_comment) prepare_mark_nocomment(prep);
			int isweak = (string_content(tok.tokv.str)[4] == 'V');
			request_t req = {
				.default_comment = is_comment,
				.has_val = 0,
				.ignored = 0,
				.obj_name = NULL,
				.weak = isweak,
				.def = {
					.rty =
						(string_content(tok.tokv.str)[isweak ? 5 : 4] == 'B') ? RQT_DATAB :
						(string_content(tok.tokv.str)[isweak ? 5 : 4] == 'M') ? RQT_DATAM : RQT_DATA,
					.dat.has_size = 0,
					.dat.sz = 0,
				},
				.val = {0},
			};
			string_del(tok.tokv.str);
			tok = pre_next_token(prep, 0);
			if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_LPAREN)) {
				log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (lparen)\n", lineno);
				preproc_token_del(&tok);
				goto failed;
			}
			// Empty destructor
			tok = pre_next_token(prep, 0);
			if (tok.tokt != PPTOK_IDENT) {
				log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (obj_name)\n", lineno);
				preproc_token_del(&tok);
				goto failed;
			}
			req.obj_name = tok.tokv.str;
			// Token moved
			tok = pre_next_token(prep, 0);
			if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_COMMA)) {
				log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (comma)\n", lineno);
				string_del(req.obj_name);
				preproc_token_del(&tok);
				goto failed;
			}
			// Empty destructor
			tok = pre_next_token(prep, 0);
			if (tok.tokt == PPTOK_NUM) {
				num_constant_t cst;
				// Assume target is 64 bits (box64)
				if (!num_constant_convert(&tok.loginfo, tok.tokv.str, &cst, 0)) {
					log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (num conversion)\n", lineno);
					string_del(req.obj_name);
					preproc_token_del(&tok);
					goto failed;
				}
				switch (cst.typ) {
				case NCT_FLOAT:
				case NCT_DOUBLE:
				case NCT_LDOUBLE:
					log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (num conversion)\n", lineno);
					string_del(req.obj_name);
					string_del(tok.tokv.str);
					goto failed;
				case NCT_INT32:  req.def.dat.sz = (size_t)cst.val.i32; break;
				case NCT_UINT32: req.def.dat.sz = (size_t)cst.val.u32; break;
				case NCT_INT64:  req.def.dat.sz = (size_t)cst.val.i64; break;
				case NCT_UINT64: req.def.dat.sz = (size_t)cst.val.u64; break;
				}
				req.def.dat.has_size = 1;
				string_del(tok.tokv.str); // Delete token
				tok = pre_next_token(prep, 0);
				if ((tok.tokt != PPTOK_SYM) || (tok.tokv.sym != SYM_RPAREN)) {
					log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (rparen)\n", lineno);
					string_del(req.obj_name);
					preproc_token_del(&tok);
					goto failed;
				}
				// Empty destructor
				tok = pre_next_token(prep, 0);
			}
			if (tok.tokt != PPTOK_NEWLINE) {
				log_error(&tok.loginfo, "invalid reference file: invalid DATA line %d (newline)\n", lineno);
				string_del(req.obj_name);
				preproc_token_del(&tok);
				goto failed;
			}
			if (!vector_push(references, ret, ((reference_t){.typ = REF_REQ, .req = req}))) {
				log_memory("failed to add reference for %s\n", string_content(req.obj_name));
				request_del(&req);
				// Empty destructor
				goto failed;
			}
			++lineno;
		} else if (is_comment) {
			if (tok.tokt == PPTOK_IDENT) {
				ADD_STR(tok.tokv.str, 1, "comment content")
				string_del(tok.tokv.str);
			} else if (tok.tokt == PPTOK_BLANK) {
				ADD_CHAR(tok.tokv.c, 0, "comment content")
			} else {
				log_error(&tok.loginfo, "unknown token type in comment %u\n", tok.tokt);
				preproc_token_del(&tok);
				goto failed;
			}
			if (!pre_next_newline_token(prep, line)) {
				log_memory("failed to add comment content\n");
				goto failed;
			}
			PUSH_LINE(0)
			++lineno;
		} else {
			log_error(&tok.loginfo, "invalid reference file: invalid token:\n");
			preproc_token_print(&tok);
			preproc_token_del(&tok);
			goto failed;
		}
	}
	
failed:
	string_del(line);
	prepare_del(prep);
	vector_del(references, ret);
	return NULL;
	
success:
	string_del(line);
	prepare_del(prep);
	return ret;
}

// Simple versions (in practice, only use x86_64 and aarch64 as emu/target pair)
static int is_simple_type_ptr_to_simple(type_t *typ, int *needs_D, int *needs_my, khash_t(conv_map) *conv_map) {
	if (typ->converted) {
		// printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
	} else if (kh_get(conv_map, conv_map, typ) != kh_end(conv_map)) {
		// printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
	}
	switch (typ->typ) {
	case TYPE_BUILTIN:
		return 1; // Assume pointers to builtin are simple
	case TYPE_ARRAY:
		if (typ->val.array.array_sz == (size_t)-1) return 0; // VLA are not simple
		return is_simple_type_ptr_to_simple(typ->val.array.typ, needs_D, needs_my, conv_map);
	case TYPE_STRUCT_UNION:
		if (typ->_internal_use) return 1; // Recursive structures are OK as long as every other members are OK
		if (!typ->val.st->is_defined) return 1; // Undefined structures are OK since they are opaque
		if (typ->val.st->is_simple) return 1;
		typ->_internal_use = 1;
		for (size_t i = 0; i < typ->val.st->nmembers; ++i) {
			st_member_t *mem = &typ->val.st->members[i];
			if (!is_simple_type_ptr_to_simple(mem->typ, needs_D, needs_my, conv_map)) {
				typ->_internal_use = 0;
				return 0;
			}
		}
		typ->_internal_use = 0;
		return 1;
	case TYPE_ENUM:
		return is_simple_type_ptr_to_simple(typ->val.typ, needs_D, needs_my, conv_map);
	case TYPE_PTR:
		return is_simple_type_ptr_to_simple(typ->val.typ, needs_D, needs_my, conv_map);
	case TYPE_FUNCTION:
		*needs_my = 1;
		return 1;
	default:
		printf("Error: is_simple_type_ptr_to_simple on unknown type %u\n", typ->typ);
		return 0;
	}
}
static int is_simple_type_simple(type_t *typ, int *needs_D, int *needs_my, khash_t(conv_map) *conv_map) {
	if (typ->converted) {
		// printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
	} else if (kh_get(conv_map, conv_map, typ) != kh_end(conv_map)) {
		// printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
	}
	switch (typ->typ) {
	case TYPE_BUILTIN:
		return (typ->val.builtin != BTT_FLOAT128)
		    && (typ->val.builtin != BTT_CFLOAT128)
		    && (typ->val.builtin != BTT_IFLOAT128); // Assume builtin are simple except for __float128
	case TYPE_ARRAY:
		if (typ->val.array.array_sz == (size_t)-1) return 0; // VLA are not simple
		return is_simple_type_ptr_to_simple(typ->val.array.typ, needs_D, needs_my, conv_map);
	case TYPE_STRUCT_UNION:
		if (typ->_internal_use) return 1; // Recursive structures are OK as long as every other members are OK
		// if (!typ->val.st->is_defined) return 1; // Undefined structures are OK since they are opaque
		// To be safe, don't allow opaque structures
		if (!typ->val.st->is_defined) return 0;
		typ->_internal_use = 1;
		for (size_t i = 0; i < typ->val.st->nmembers; ++i) {
			st_member_t *mem = &typ->val.st->members[i];
			if (!is_simple_type_simple(mem->typ, needs_D, needs_my, conv_map)) {
				typ->_internal_use = 0;
				return 0;
			}
		}
		typ->_internal_use = 0;
		return 1;
	case TYPE_ENUM:
		return is_simple_type_simple(typ->val.typ, needs_D, needs_my, conv_map);
	case TYPE_PTR:
		return is_simple_type_ptr_to_simple(typ->val.typ, needs_D, needs_my, conv_map);
	case TYPE_FUNCTION:
		// Functions should be handled differently (GO instead of DATA)
		return 0;
	default:
		printf("Error: is_simple_type_simple on unknown type %u\n", typ->typ);
		return 0;
	}
}

static int convert_type_simple(string_t *dest, type_t *emu_typ, type_t *target_typ,
                               int is_ret, int *needs_D, int *needs_my, khash_t(conv_map) *conv_map, string_t *obj_name) {
	if (emu_typ->converted) {
		if (!string_add_string(dest, emu_typ->converted)) {
			printf("Error: failed to add explicit type conversion\n");
			return 0;
		}
		return 1;
	}
	khiter_t it = kh_get(conv_map, conv_map, emu_typ);
	if (it != kh_end(conv_map)) {
		if (!string_add_string(dest, kh_val(conv_map, it))) {
			printf("Error: failed to add explicit type conversion\n");
			return 0;
		}
		return 1;
	}
	if ((emu_typ->is_atomic) || (target_typ->is_atomic)) {
		printf("Error: TODO: convert_type_simple for atomic types\n");
		return 0;
	}
	if (emu_typ->typ != target_typ->typ) {
		printf("Error: %s: %s type is different between emulated and target\n", string_content(obj_name), is_ret ? "return" : "argument");
		*needs_my = 1;
	}
	switch (emu_typ->typ) {
	case TYPE_BUILTIN: {
		int has_char = 0;
		char c;
		switch (emu_typ->val.builtin) {
		case BTT_VOID: has_char = 1; c = 'v'; break;
		case BTT_BOOL: has_char = 1; c = 'i'; break;
		case BTT_CHAR: has_char = 1; c = 'c'; break;
		case BTT_SCHAR: has_char = 1; c = 'c'; break;
		case BTT_UCHAR: has_char = 1; c = 'C'; break;
		case BTT_SHORT: has_char = 1; c = 'w'; break;
		case BTT_SSHORT: has_char = 1; c = 'w'; break;
		case BTT_USHORT: has_char = 1; c = 'W'; break;
		case BTT_INT: has_char = 1; c = 'i'; break;
		case BTT_SINT: has_char = 1; c = 'i'; break;
		case BTT_UINT: has_char = 1; c = 'u'; break;
		case BTT_LONG: has_char = 1; c = 'l'; break;
		case BTT_SLONG: has_char = 1; c = 'l'; break;
		case BTT_ULONG: has_char = 1; c = 'L'; break;
		case BTT_LONGLONG: has_char = 1; c = 'I'; break;
		case BTT_SLONGLONG: has_char = 1; c = 'I'; break;
		case BTT_ULONGLONG: has_char = 1; c = 'U'; break;
		case BTT_INT128: has_char = 1; c = 'H'; break; // TODO: Is 'H' for signed and unsigned?
		case BTT_SINT128: has_char = 1; c = 'H'; break; // Is 'H' for signed and unsigned?
		case BTT_UINT128: has_char = 1; c = 'H'; break; // Is 'H' for signed and unsigned?
		case BTT_S8: has_char = 1; c = 'c'; break;
		case BTT_U8: has_char = 1; c = 'C'; break;
		case BTT_S16: has_char = 1; c = 'w'; break;
		case BTT_U16: has_char = 1; c = 'W'; break;
		case BTT_S32: has_char = 1; c = 'i'; break;
		case BTT_U32: has_char = 1; c = 'u'; break;
		case BTT_S64: has_char = 1; c = 'I'; break;
		case BTT_U64: has_char = 1; c = 'U'; break;
		case BTT_FLOAT: has_char = 1; c = 'f'; break;
		case BTT_CFLOAT: has_char = 1; c = 'x'; break;
		case BTT_IFLOAT: has_char = 1; c = 'f'; break;
		case BTT_DOUBLE: has_char = 1; c = 'd'; break;
		case BTT_CDOUBLE: has_char = 1; c = 'X'; break;
		case BTT_IDOUBLE: has_char = 1; c = 'd'; break;
		case BTT_LONGDOUBLE: *needs_D = 1; has_char = 1; c = 'D'; break;
		case BTT_CLONGDOUBLE: *needs_D = 1; has_char = 1; c = 'Y'; break;
		case BTT_ILONGDOUBLE: *needs_D = 1; has_char = 1; c = 'D'; break;
		case BTT_FLOAT128: printf("Error: TODO: %s\n", builtin2str[emu_typ->val.builtin]); return 0;
		case BTT_CFLOAT128: printf("Error: TODO: %s\n", builtin2str[emu_typ->val.builtin]); return 0;
		case BTT_IFLOAT128: printf("Error: TODO: %s\n", builtin2str[emu_typ->val.builtin]); return 0;
		case BTT_VA_LIST: *needs_my = 1; has_char = 1; c = 'A'; break;
		default:
			printf("Error: convert_type_simple on unknown builtin %u\n", emu_typ->val.builtin);
			return 0;
		}
		if (has_char) {
			if (!string_add_char(dest, c)) {
				printf("Error: failed to add type char for %s\n", builtin2str[emu_typ->val.builtin]);
				return 0;
			}
			return 1;
		} else {
			printf("Internal error: unknown state builtin=%u\n", emu_typ->val.builtin);
			return 0;
		} }
	case TYPE_ARRAY:
		printf("Error: convert_type_simple on raw array\n");
		return 0;
	case TYPE_STRUCT_UNION:
		if (!emu_typ->is_validated || emu_typ->is_incomplete) {
			printf("Error: incomplete structure for %s\n", string_content(obj_name));
			return 0;
		}
		if (is_ret) {
			if (emu_typ->szinfo.size <= 8) {
				if (!string_add_char(dest, 'U')) {
					printf("Error: failed to add type char for structure return\n");
					return 0;
				}
				return 1;
			} else if (emu_typ->szinfo.size <= 16) {
				if (!string_add_char(dest, 'H')) {
					printf("Error: failed to add type char for large structure return\n");
					return 0;
				}
				return 1;
			} else {
				if (!string_add_char(dest, 'p')) {
					printf("Error: failed to add type char for very large structure return\n");
					return 0;
				}
				return 1;
			}
		} else {
			if ((emu_typ->val.st->nmembers == 1) && (target_typ->typ == TYPE_STRUCT_UNION) && (target_typ->val.st->nmembers == 1)) {
				return convert_type_simple(dest, emu_typ->val.st->members[0].typ, target_typ->val.st->members[0].typ, is_ret, needs_D, needs_my, conv_map, obj_name);
			}
			printf("Error: TODO: convert_type_simple on structure as argument (%s)\n", string_content(obj_name));
			return 0;
		}
	case TYPE_ENUM:
		if (target_typ->typ == TYPE_ENUM) {
			return convert_type_simple(dest, emu_typ->val.typ, target_typ->val.typ, is_ret, needs_D, needs_my, conv_map, obj_name);
		} else {
			printf("Fatal: convert_type_simple(enum, non-enum)\n");
			return 0;
		}
	case TYPE_PTR:
		if (is_simple_type_ptr_to_simple(emu_typ->val.typ, needs_D, needs_my, conv_map)) {
			if (!string_add_char(dest, 'p')) {
				printf("Error: failed to add type char for simple pointer\n");
				return 0;
			}
			return 1;
		} else {
			*needs_my = 1;
			if (!string_add_char(dest, 'p')) {
				printf("Error: failed to add type char for complex pointer\n");
				return 0;
			}
			return 1;
		}
	case TYPE_FUNCTION:
		printf("Error: convert_type_simple on raw function\n");
		return 0;
	default:
		printf("Error: convert_type_simple on unknown type %u\n", emu_typ->typ);
		return 0;
	}
}
static int convert_type_post_simple(string_t *dest, type_t *emu_typ, type_t *target_typ, string_t *obj_name) {
	if (emu_typ->converted) return 1;
	if (emu_typ->is_atomic) {
		printf("Error: TODO: convert_type_post_simple for atomic types\n");
		return 0;
	}
	(void)target_typ;
	switch (emu_typ->typ) {
	case TYPE_BUILTIN: return 1;
	case TYPE_ARRAY: return 1;
	case TYPE_STRUCT_UNION:
		if (!emu_typ->is_validated || emu_typ->is_incomplete) {
			printf("Error: incomplete structure for %s\n", string_content(obj_name));
			return 0;
		}
		if (emu_typ->szinfo.size <= 16) {
			return 1;
		} else {
			if (!string_add_char(dest, 'p')) {
				printf("Error: failed to add type char for very large structure return as parameter\n");
				return 0;
			}
			return 2;
		}
	case TYPE_ENUM: return 1;
	case TYPE_PTR: return 1;
	case TYPE_FUNCTION: return 1;
	}
	printf("Error: convert_type_post_simple on unknown type %u\n", emu_typ->typ);
	return 0;
}

int solve_request_simple(request_t *req, type_t *emu_typ, type_t *target_typ, khash_t(conv_map) *conv_map) {
	if (emu_typ->typ != target_typ->typ) {
		printf("Error: %s: emulated and target types are different (emulated is %u, target is %u)\n",
			string_content(req->obj_name), emu_typ->typ, target_typ->typ);
		return 0;
	}
	if (emu_typ->typ == TYPE_FUNCTION) {
		int needs_D = 0, needs_my = req->def.fun.typ && (req->def.rty == RQT_FUN_MY), needs_2 = 0;
		int convert_post;
		size_t idx_conv;
		req->val.fun.typ = string_new();
		if (!req->val.fun.typ) {
			printf("Error: failed to create function type string\n");
			return 0;
		}
		if (!convert_type_simple(req->val.fun.typ, emu_typ->val.fun.ret, target_typ->val.fun.ret, 1, &needs_D, &needs_my, conv_map, req->obj_name))
			goto fun_fail;
		idx_conv = string_len(req->val.fun.typ);
		if (!string_add_char(req->val.fun.typ, 'F')) {
			printf("Error: failed to add convention char\n");
			goto fun_fail;
		}
		convert_post = convert_type_post_simple(req->val.fun.typ, emu_typ->val.fun.ret, target_typ->val.fun.ret, req->obj_name);
		if (!convert_post) goto fun_fail;
		if (emu_typ->val.fun.nargs == (size_t)-1) {
			printf("Warning: %s: assuming empty specification is void specification\n", string_content(req->obj_name));
			if (convert_post == 1) {
				if (!string_add_char(req->val.fun.typ, 'v')) {
					printf("Error: failed to add void specification char\n");
					goto fun_fail;
				}
			}
		} else if (!emu_typ->val.fun.nargs && !emu_typ->val.fun.has_varargs) {
			if (convert_post == 1) {
				if (!string_add_char(req->val.fun.typ, 'v')) {
					printf("Error: failed to add void specification char\n");
					goto fun_fail;
				}
			}
		} else {
			for (size_t i = 0; i < emu_typ->val.fun.nargs; ++i) {
				if (!convert_type_simple(req->val.fun.typ, emu_typ->val.fun.args[i], target_typ->val.fun.args[i], 0, &needs_D, &needs_my, conv_map, req->obj_name))
					goto fun_fail;
			}
			if (emu_typ->val.fun.has_varargs) {
				if (req->def.fun.typ
				      && (string_len(req->def.fun.typ) == string_len(req->val.fun.typ) + 1)
				      && !strncmp(string_content(req->def.fun.typ), string_content(req->val.fun.typ), string_len(req->val.fun.typ))
				      && ((string_content(req->def.fun.typ)[string_len(req->val.fun.typ)] == 'M')
				       || (string_content(req->def.fun.typ)[string_len(req->val.fun.typ)] == 'N'))) {
					if (!string_add_char(req->val.fun.typ, string_content(req->def.fun.typ)[string_len(req->val.fun.typ)])) {
						printf("Error: failed to add type char '%c' for %s\n",
							string_content(req->def.fun.typ)[string_len(req->val.fun.typ)],
							builtin2str[emu_typ->val.builtin]);
						goto fun_fail;
					}
				} else {
					needs_my = 1;
					if (!string_add_char(req->val.fun.typ, 'V')) {
						printf("Error: failed to add type char 'V' for %s\n", builtin2str[emu_typ->val.builtin]);
						goto fun_fail;
					}
				}
			}
		}
		
	// fun_succ:
		// Add 'E' by default, unless we have the same function as before
		if (needs_my && (req->default_comment
		                  || (req->def.rty != RQT_FUN_MY)
		                  || strcmp(string_content(req->def.fun.typ), string_content(req->val.fun.typ)))) {
			if (!string_add_char_at(req->val.fun.typ, 'E', idx_conv + 1)) {
				printf("Error: failed to add emu char\n");
				goto fun_fail;
			}
		}
		if (req->def.fun.typ && (req->def.rty == RQT_FUN_2) && !needs_my) {
			needs_2 = 1;
			req->val.fun.fun2 = string_dup(req->def.fun.fun2);
			if (!req->val.fun.fun2) {
				printf("Error: failed to duplicate string (request for function %s with default redirection)\n", string_content(req->obj_name));
				return 0;
			}
		} else if (req->def.fun.typ && (req->def.rty == RQT_FUN_D) && !needs_my) {
			needs_2 = 0;
			req->val.fun.fun2 = string_dup(req->def.fun.fun2);
			if (!req->val.fun.fun2) {
				printf("Error: failed to duplicate string (request for function %s with long double types)\n", string_content(req->obj_name));
				return 0;
			}
		} else if (!needs_my && needs_D) {
			req->val.fun.fun2 = string_new();
			if (!req->val.fun.fun2) {
				printf("Error: failed to create empty string (request for function %s with long double types)\n", string_content(req->obj_name));
				return 0;
			}
		}
		req->val.rty =
			needs_my ? RQT_FUN_MY :
			needs_2 ? RQT_FUN_2 :
			needs_D ? RQT_FUN_D : RQT_FUN;
		req->has_val = 1;
		return 1;
		
	fun_fail:
		string_del(req->val.fun.typ);
		return 0;
	} else {
		int needs_D = 0, needs_my = req->def.dat.has_size && (req->def.rty == RQT_DATAM);
		if (is_simple_type_simple(emu_typ, &needs_D, &needs_my, conv_map)) {
			// TODO: Hmm...
			req->val.rty = needs_my ? RQT_DATAM : (IS_RQT_FUNCTION(req->def.rty) ? RQT_DATA : req->def.rty);
			req->val.dat.has_size = 1;
			req->val.dat.sz = emu_typ->szinfo.size;
			req->has_val = 1;
			return 1;
		} else {
			log_TODO_nopos("solve_request_simple for data %s with non-simple type ", string_content(req->obj_name));
			type_print(emu_typ);
			printf("\n");
			return 0;
		}
	}
}
int solve_request_map_simple(request_t *req, khash_t(decl_map) *emu_decl_map, khash_t(decl_map) *target_decl_map, khash_t(conv_map) *conv_map) {
	int hasemu = 0, hastarget = 0;
	khiter_t emuit, targetit;
	emuit = kh_get(decl_map, emu_decl_map, string_content(req->obj_name));
	if (emuit == kh_end(emu_decl_map)) {
		goto failed;
	}
	if ((kh_val(emu_decl_map, emuit)->storage == STORAGE_STATIC) || (kh_val(emu_decl_map, emuit)->storage == STORAGE_TLS_STATIC)) {
		goto failed;
	}
	targetit = kh_get(decl_map, target_decl_map, string_content(req->obj_name));
	if (targetit == kh_end(target_decl_map)) {
		goto failed;
	}
	if ((kh_val(target_decl_map, targetit)->storage == STORAGE_STATIC) || (kh_val(target_decl_map, targetit)->storage == STORAGE_TLS_STATIC)) {
		goto failed;
	}
	return solve_request_simple(req, kh_val(emu_decl_map, emuit)->typ, kh_val(target_decl_map, targetit)->typ, conv_map);
	
failed:
	if (string_content(req->obj_name)[0] != '_') {
		if (!hasemu && !hastarget) {
			printf("Error: %s was not declared in the emulated and target architectures\n", string_content(req->obj_name));
		} else if (!hasemu) {
			printf("Error: %s was not declared only in the emulated architecture\n", string_content(req->obj_name));
		} else if (!hastarget) {
			printf("Error: %s was not declared only in the target architecture\n", string_content(req->obj_name));
		} else {
			printf("Error: internal error: failed but found for %s\n", string_content(req->obj_name));
		}
	}
	return 0;
}
int solve_references_simple(VECTOR(references) *refs, khash_t(decl_map) *emu_decl_map, khash_t(decl_map) *target_decl_map, khash_t(conv_map) *conv_map) {
	int ret = 1;
	int cond_depth = 0, ok_depth = 0;
	vector_for(references, ref, refs) {
		switch (ref->typ) {
		case REF_REQ:
			if (ok_depth == cond_depth) {
				if (!solve_request_map_simple(&ref->req, emu_decl_map, target_decl_map, conv_map)) ret = 0;
			} else {
				ref->req.ignored = 1;
			}
			break;
		case REF_LINE:
			break;
		case REF_IFDEF:
			++cond_depth;
			break;
		case REF_IFNDEF:
			if (cond_depth == ok_depth) ++ok_depth;
			++cond_depth;
			break;
		case REF_ELSE:
			if (cond_depth == ok_depth) --ok_depth;
			else if (cond_depth == ok_depth + 1) ++ok_depth;
			break;
		case REF_ENDIF:
			if (cond_depth == ok_depth) --ok_depth;
			--cond_depth;
			break;
		}
	}
	return ret;
}

// Complex versions
enum safeness_e {
	SAFE_ABORT,  // Failure
	SAFE_OK,     // Simple, can output 'p'
	SAFE_EXPAND, // Complex but automatable, needs to output 'b..._'
};
static enum safeness_e get_safeness_ptr(type_t *emu_typ, type_t *target_typ, int *needs_D, int *needs_my, khash_t(conv_map) *conv_map, string_t *obj_name) {
	if (emu_typ->typ != target_typ->typ) {
		printf("Error: %s: pointer with different types between emu and target\n", string_content(obj_name));
		return SAFE_ABORT;
	}
	if (emu_typ->converted) {
		printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
		return SAFE_OK;
	} else if (kh_get(conv_map, conv_map, emu_typ) != kh_end(conv_map)) {
		printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
		return SAFE_OK;
	}
	switch (emu_typ->typ) {
	case TYPE_BUILTIN:
		if (emu_typ->val.builtin != target_typ->val.builtin) {
			// printf("Warning: %s: emu and target have pointers to different size type\n", string_content(obj_name));
			return SAFE_ABORT;
		}
		if (emu_typ->szinfo.size != target_typ->szinfo.size) {
			// printf("Warning: %s: emu and target have pointers to different size type\n", string_content(obj_name));
			return SAFE_EXPAND;
		}
		/* if (emu_typ->szinfo.align != target_typ->szinfo.align) {
			// printf("Warning: %s: emu and target have pointers to different alignment type\n", string_content(obj_name));
			return SAFE_EXPAND;
		} */
		// Assume pointers to builtins of the same size and alignment are simple
		return SAFE_OK;
	case TYPE_ARRAY:
		if (emu_typ->szinfo.size != target_typ->szinfo.size) {
			// printf("Warning: %s: emu and target have pointers to arrays with different size type\n", string_content(obj_name));
			return SAFE_EXPAND;
		}
		if (emu_typ->szinfo.align != target_typ->szinfo.align) {
			// printf("Warning: %s: emu and target have pointers to arrays with different alignment type\n", string_content(obj_name));
			return SAFE_EXPAND;
		}
		if (emu_typ->val.array.array_sz != target_typ->val.array.array_sz) {
			printf("Error: %s: emu and target have arrays of different size\n", string_content(obj_name));
			return SAFE_ABORT; // Shouldn't happen
		}
		// Elements also have the same size
		if ((emu_typ->val.array.array_sz == (size_t)-1) || (target_typ->val.array.array_sz == (size_t)-1)) {
			printf("Error: %s: has variable length arrays\n", string_content(obj_name));
			return SAFE_ABORT; // VLA require manual intervention
		}
		return get_safeness_ptr(emu_typ->val.array.typ, target_typ->val.array.typ, needs_D, needs_my, conv_map, obj_name);
	case TYPE_STRUCT_UNION:
		if (emu_typ->val.st->is_struct != target_typ->val.st->is_struct) {
			printf("Error: %s: incoherent struct/union type between emulated and target architectures for %s\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_ABORT;
		}
		if (emu_typ->is_incomplete != target_typ->is_incomplete) {
			printf("Error: %s: incoherent struct/union completion type between emulated and target architectures for %s\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_ABORT;
		}
		if (emu_typ->is_incomplete) {
			return SAFE_OK; // Undefined structures are OK since they are opaque
		}
		if (emu_typ->val.st->nmembers != target_typ->val.st->nmembers) {
			printf("Error: %s: struct/union %s has different number of members between emulated and target architectures\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_ABORT;
		}
		if (emu_typ->val.st->has_self_recursion) {
			// Self-reference implies manual intervention
			*needs_my = 1;
			return SAFE_OK;
		}
		if (emu_typ->val.st->nmembers == 1) {
			// Assume structs and unions of one element has the same ABI as that element directly
			return get_safeness_ptr(emu_typ->val.st->members[0].typ, target_typ->val.st->members[0].typ, needs_D, needs_my, conv_map, obj_name);
		}
		if (emu_typ->val.st->is_struct) {
			// Structures are OK if all named members are OK and at the same memory offset
			for (size_t i = 0; i < emu_typ->val.st->nmembers; ++i) {
				st_member_t *emu_mem = &emu_typ->val.st->members[i];
				st_member_t *target_mem = &target_typ->val.st->members[i];
				if (emu_mem->name) {
					if ((emu_mem->byte_offset != target_mem->byte_offset) || (emu_mem->bit_offset != target_mem->bit_offset)) {
						return SAFE_EXPAND;
					}
					enum safeness_e saf = get_safeness_ptr(emu_mem->typ, target_mem->typ, needs_D, needs_my, conv_map, obj_name);
					if (saf != SAFE_OK) return saf;
				}
			}
			return SAFE_OK;
		} else {
			// Unions are OK if all named members are OK (memory offset is always 0)
			for (size_t i = 0; i < emu_typ->val.st->nmembers; ++i) {
				st_member_t *emu_mem = &emu_typ->val.st->members[i];
				st_member_t *target_mem = &target_typ->val.st->members[i];
				if (emu_mem->name) {
					enum safeness_e saf = get_safeness_ptr(emu_mem->typ, target_mem->typ, needs_D, needs_my, conv_map, obj_name);
					if (saf != SAFE_OK) return saf;
				}
			}
			return SAFE_OK;
		}
	case TYPE_ENUM:
		return get_safeness_ptr(emu_typ->val.typ, target_typ->val.typ, needs_D, needs_my, conv_map, obj_name);
	case TYPE_PTR:
		return SAFE_EXPAND;
	case TYPE_FUNCTION:
		*needs_my = 1;
		return SAFE_OK;
	default:
		printf("Error: get_safeness_ptr on unknown type %u\n", emu_typ->typ);
		return SAFE_ABORT;
	}
}
static enum safeness_e get_safeness(type_t *emu_typ, type_t *target_typ, int *needs_D, int *needs_my, khash_t(conv_map) *conv_map, string_t *obj_name) {
	if (emu_typ->typ != target_typ->typ) {
		printf("Error: %s: data with different types between emu and target\n", string_content(obj_name));
		return SAFE_ABORT; // Invalid type
	}
	if (emu_typ->converted) {
		// printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
		return SAFE_OK;
	} else if (kh_get(conv_map, conv_map, emu_typ) != kh_end(conv_map)) {
		// printf("Warning: %s uses a converted type but is not the converted type\n", string_content(obj_name));
		*needs_my = 1;
		return SAFE_OK;
	}
	switch (emu_typ->typ) {
	case TYPE_BUILTIN:
		if ((emu_typ->val.builtin != target_typ->val.builtin)
		    || (emu_typ->szinfo.size != target_typ->szinfo.size)
		    || (emu_typ->szinfo.align != target_typ->szinfo.align)
		    || (emu_typ->val.builtin == BTT_FLOAT128)
		    || (emu_typ->val.builtin == BTT_CFLOAT128)
		    || (emu_typ->val.builtin == BTT_IFLOAT128)) {
			// Assume all builtins are simple except for __float128 and those with different size or alignment
			*needs_my = 1;
		}
		return SAFE_OK;
	case TYPE_ARRAY:
		if (emu_typ->szinfo.size != target_typ->szinfo.size) {
			// printf("Warning: %s: emu and target have pointers to different size type\n", string_content(obj_name));
			return SAFE_EXPAND;
		}
		if (emu_typ->szinfo.align != target_typ->szinfo.align) {
			// printf("Warning: %s: emu and target have pointers to different alignment type\n", string_content(obj_name));
			return SAFE_EXPAND;
		}
		if (emu_typ->val.array.array_sz != target_typ->val.array.array_sz) {
			printf("Error: %s: emu and target have arrays of different size\n", string_content(obj_name));
			return SAFE_ABORT; // Shouldn't happen
		}
		// Elements also have the same size
		if ((emu_typ->val.array.array_sz == (size_t)-1) || (target_typ->val.array.array_sz == (size_t)-1)) {
			printf("Error: %s: has variable length arrays\n", string_content(obj_name));
			return SAFE_ABORT; // VLA require manual intervention
		}
		return get_safeness_ptr(emu_typ->val.array.typ, target_typ->val.array.typ, needs_D, needs_my, conv_map, obj_name);
	case TYPE_STRUCT_UNION:
		if (emu_typ->val.st->is_struct != target_typ->val.st->is_struct) {
			printf("Error: %s: incoherent struct/union type between emulated and target architectures for %s\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_ABORT;
		}
		if (emu_typ->is_incomplete != target_typ->is_incomplete) {
			printf("Error: %s: incoherent struct/union completion type between emulated and target architectures for %s\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_ABORT;
		}
		if (emu_typ->is_incomplete) {
			printf("Warning: %s: undefined struct/union %s considered as simple\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_OK; // Assume undefined structures are OK since they are opaque
		}
		if (emu_typ->val.st->nmembers != target_typ->val.st->nmembers) {
			printf("Error: %s: struct/union %s has different number of members between emulated and target architectures\n",
				string_content(obj_name), emu_typ->val.st->tag ? string_content(emu_typ->val.st->tag) : "<no tag>");
			return SAFE_ABORT;
		}
		if (emu_typ->val.st->has_self_recursion) {
			// Self-reference implies manual intervention
			*needs_my = 1;
			return SAFE_OK;
		}
		for (size_t i = 0; i < emu_typ->val.st->nmembers; ++i) {
			switch (get_safeness(emu_typ->val.st->members[i].typ, target_typ->val.st->members[i].typ, needs_D, needs_my, conv_map, obj_name)) {
			case SAFE_OK: break;
			case SAFE_ABORT:
			case SAFE_EXPAND:
			default: return SAFE_ABORT;
			}
		}
		return SAFE_OK;
	case TYPE_ENUM:
		return get_safeness(emu_typ->val.typ, target_typ->val.typ, needs_D, needs_my, conv_map, obj_name);
	case TYPE_PTR:
		// Pointers have different sizes here
		return SAFE_EXPAND;
	case TYPE_FUNCTION:
		// Functions should be handled differently (GO instead of DATA)
		return SAFE_ABORT;
	default:
		printf("Error: get_safeness on unknown type %u\n", emu_typ->typ);
		return SAFE_ABORT;
	}
}

// needs_S != NULL iff type is return
static int convert_type(string_t *dest, type_t *emu_typ, type_t *target_typ, int allow_nesting,
                        _Bool *needs_S, int *needs_D, int *needs_my, khash_t(conv_map) *conv_map, string_t *obj_name) {
	if (emu_typ->converted) {
		if (!string_add_string(dest, emu_typ->converted)) {
			printf("Error: failed to add explicit type conversion\n");
			return 0;
		}
		return 1;
	}
	khiter_t it = kh_get(conv_map, conv_map, emu_typ);
	if (it != kh_end(conv_map)) {
		if (!string_add_string(dest, kh_val(conv_map, it))) {
			printf("Error: failed to add explicit type conversion\n");
			return 0;
		}
		return 1;
	}
	if ((emu_typ->is_atomic) || (target_typ->is_atomic)) {
		printf("Error: TODO: convert_type for atomic types\n");
		return 0;
	}
	if (emu_typ->typ != target_typ->typ) {
		printf("Error: %s: %s type is different between emulated and target\n", string_content(obj_name), needs_S ? "return" : "argument");
		return 0;
	}
	switch (emu_typ->typ) {
	case TYPE_BUILTIN: {
		int has_char = 0;
		char c;
		switch (emu_typ->val.builtin) {
		case BTT_VOID: has_char = 1; c = 'v'; break;
		case BTT_BOOL: has_char = 1; c = 'i'; break;
		case BTT_CHAR: has_char = 1; c = 'c'; break;
		case BTT_SCHAR: has_char = 1; c = 'c'; break;
		case BTT_UCHAR: has_char = 1; c = 'C'; break;
		case BTT_SHORT: has_char = 1; c = 'w'; break;
		case BTT_SSHORT: has_char = 1; c = 'w'; break;
		case BTT_USHORT: has_char = 1; c = 'W'; break;
		case BTT_INT: has_char = 1; c = 'i'; break;
		case BTT_SINT: has_char = 1; c = 'i'; break;
		case BTT_UINT: has_char = 1; c = 'u'; break;
		case BTT_LONG: has_char = 1; c = 'l'; break;
		case BTT_SLONG: has_char = 1; c = 'l'; break;
		case BTT_ULONG: has_char = 1; c = 'L'; break;
		case BTT_LONGLONG: has_char = 1; c = 'I'; break;
		case BTT_SLONGLONG: has_char = 1; c = 'I'; break;
		case BTT_ULONGLONG: has_char = 1; c = 'U'; break;
		case BTT_INT128: has_char = 1; c = 'H'; break;
		case BTT_SINT128: has_char = 1; c = 'H'; break;
		case BTT_UINT128: has_char = 1; c = 'H'; break;
		case BTT_S8: has_char = 1; c = 'c'; break;
		case BTT_U8: has_char = 1; c = 'C'; break;
		case BTT_S16: has_char = 1; c = 'w'; break;
		case BTT_U16: has_char = 1; c = 'W'; break;
		case BTT_S32: has_char = 1; c = 'i'; break;
		case BTT_U32: has_char = 1; c = 'u'; break;
		case BTT_S64: has_char = 1; c = 'I'; break;
		case BTT_U64: has_char = 1; c = 'U'; break;
		case BTT_FLOAT: has_char = 1; c = 'f'; break;
		case BTT_CFLOAT: has_char = 1; c = 'x'; break;
		case BTT_IFLOAT: has_char = 1; c = 'f'; break;
		case BTT_DOUBLE: has_char = 1; c = 'd'; break;
		case BTT_CDOUBLE: has_char = 1; c = 'X'; break;
		case BTT_IDOUBLE: has_char = 1; c = 'd'; break;
		case BTT_LONGDOUBLE: *needs_D = 1; has_char = 1; c = 'D'; break;
		case BTT_CLONGDOUBLE: *needs_D = 1; has_char = 1; c = 'Y'; break;
		case BTT_ILONGDOUBLE: *needs_D = 1; has_char = 1; c = 'D'; break;
		case BTT_FLOAT128: printf("Error: TODO: %s\n", builtin2str[emu_typ->val.builtin]); return 0;
		case BTT_CFLOAT128: printf("Error: TODO: %s\n", builtin2str[emu_typ->val.builtin]); return 0;
		case BTT_IFLOAT128: printf("Error: TODO: %s\n", builtin2str[emu_typ->val.builtin]); return 0;
		case BTT_VA_LIST: *needs_my = 1; has_char = 1; c = 'p'; break;
		default:
			printf("Error: convert_type on unknown builtin %u\n", emu_typ->val.builtin);
			return 0;
		}
		if (has_char) {
			if (!string_add_char(dest, c)) {
				printf("Error: failed to add type char for complex pointer\n");
				return 0;
			}
			return 1;
		} else {
			printf("Internal error: unknown state builtin=%u\n", emu_typ->val.builtin);
			return 0;
		} }
	case TYPE_ARRAY: {
		// May come from the content of a pointer or structure
		if ((emu_typ->val.array.array_sz == (size_t)-1) || (target_typ->val.array.array_sz == (size_t)-1)) {
			printf("Error: %s: has variable length arrays\n", string_content(obj_name));
			return 0; // VLA require manual intervention
		}
		if (emu_typ->val.array.array_sz != target_typ->val.array.array_sz) {
			printf("Error: %s: emu and target have arrays of different size\n", string_content(obj_name));
			return 0; // Shouldn't happen
		}
		if (!emu_typ->val.array.array_sz) {
			// printf("Warning: %s: has zero-length array\n", string_content(obj_name));
			return 1;
		}
		size_t idx = string_len(dest);
		if (!convert_type(dest, emu_typ->val.array.typ, target_typ->val.array.typ, allow_nesting, needs_S, needs_D, needs_my, conv_map, obj_name))
			return 0;
		size_t end = string_len(dest);
		if (idx == end) return 1;
		if (!string_reserve(dest, idx + (end - idx) * emu_typ->val.array.array_sz)) {
			printf("Error: failed to reserve string capacity (for array of type conversing length %zu and size %zu)\n",
				end - idx, emu_typ->val.array.array_sz);
			return 0;
		}
		for (size_t i = 1; i < emu_typ->val.array.array_sz; ++i) {
			memcpy(string_content(dest) + idx + (end - idx) * i, string_content(dest) + idx, end - idx);
			// HACKHACKHACK ===
			string_len(dest) += end - idx;
			// === HACKHACKHACK
		}
		return 1; }
	case TYPE_STRUCT_UNION:
		if (!emu_typ->is_validated || emu_typ->is_incomplete) {
			printf("Error: incomplete structure for %s\n", string_content(obj_name));
			return 0;
		}
		if (needs_S) {
			*needs_S = 1;
			// TODO: remove this and add support in the python wrappers for structure returns
			if (!string_add_char(dest, 'p')) {
				printf("Error: failed to add type char for very large structure return\n");
				return 0;
			}
			return 1;
		} else {
			if ((emu_typ->val.st->nmembers == 1) && (target_typ->typ == TYPE_STRUCT_UNION) && (target_typ->val.st->nmembers == 1)) {
				return convert_type(dest, emu_typ->val.st->members[0].typ, target_typ->val.st->members[0].typ, allow_nesting, needs_S, needs_D, needs_my, conv_map, obj_name);
			}
			printf("Error: TODO: convert_type on structure as argument (%s)\n", string_content(obj_name));
			return 0;
		}
	case TYPE_ENUM:
		return convert_type(dest, emu_typ->val.typ, target_typ->val.typ, allow_nesting, needs_S, needs_D, needs_my, conv_map, obj_name);
	case TYPE_PTR:
		switch (get_safeness_ptr(emu_typ->val.typ, target_typ->val.typ, needs_D, needs_my, conv_map, obj_name)) {
		default:
			printf("Internal error: %s: pointer to unknown type\n", string_content(obj_name));
			return 0;
			
		case SAFE_ABORT:
			return 0;
			
		case SAFE_OK:
			if (!string_add_char(dest, 'p')) {
				printf("Error: failed to add type char for simple pointer\n");
				return 0;
			}
			return 1;
			
		case SAFE_EXPAND:
			if (!allow_nesting) {
				// TODO remove this with a better rebuild_wrappers.py
				*needs_my = 1;
				if (!string_add_char(dest, 'p')) {
					printf("Error: failed to add type char for simple pointer\n");
					return 0;
				}
				return 1;
			}
			if (!string_add_char(dest, emu_typ->is_const ? 'r' : 'b')) {
				printf("Error: failed to add start type char for wrapping pointer\n");
				return 0;
			}
			// Find the underlying type to convert
			emu_typ = emu_typ->val.typ;
			target_typ = target_typ->val.typ;
		do_expanded:
			switch (emu_typ->typ) {
			case TYPE_BUILTIN:
				if (!convert_type(dest, emu_typ, target_typ, 0, needs_S, needs_D, needs_my, conv_map, obj_name)) {
					return 0;
				}
				break;
			case TYPE_ARRAY:
				if (!convert_type(dest, emu_typ, target_typ, 0, needs_S, needs_D, needs_my, conv_map, obj_name)) {
					return 0;
				}
				break;
			case TYPE_STRUCT_UNION:
				if (!emu_typ->val.st->is_defined) {
					printf("Internal error: EXPAND with undefined struct/union ptr\n");
					return 0;
				}
				if (emu_typ->val.st->nmembers == 1) { // Single-member struct/union
					emu_typ = emu_typ->val.st->members[0].typ;
					target_typ = target_typ->val.st->members[0].typ;
					goto do_expanded;
				}
				for (size_t i = 0; i < emu_typ->val.st->nmembers; ++i) {
					if (!convert_type(dest, emu_typ->val.st->members[i].typ, target_typ->val.st->members[i].typ, 0, needs_S, needs_D, needs_my, conv_map, obj_name)) {
						return 0;
					}
				}
				break;
			case TYPE_ENUM:
				emu_typ = emu_typ->val.typ;
				target_typ = target_typ->val.typ;
				if (!convert_type(dest, emu_typ, target_typ, 0, needs_S, needs_D, needs_my, conv_map, obj_name)) {
					return 0;
				}
				break;
			case TYPE_PTR:
				if (!convert_type(dest, emu_typ, target_typ, 0, needs_S, needs_D, needs_my, conv_map, obj_name)) {
					return 0;
				}
				break;
			case TYPE_FUNCTION:
				if (!convert_type(dest, emu_typ, target_typ, 0, needs_S, needs_D, needs_my, conv_map, obj_name)) {
					return 0;
				}
				break;
			}
			if (!string_add_char(dest, '_')) {
				printf("Error: failed to add end type char for wrapping pointer\n");
				return 0;
			}
			return 1;
		}
	case TYPE_FUNCTION:
		printf("Internal error: convert_type on raw function\n");
		return 1;
	default:
		printf("Error: convert_type on unknown type %u\n", emu_typ->typ);
		return 0;
	}
}
// TODO: move this function to the python script (implement correct structure returns)
static int convert_type_post(string_t *dest, type_t *emu_typ, type_t *target_typ, string_t *obj_name) {
	if (emu_typ->converted) return 1;
	if (emu_typ->is_atomic) {
		printf("Error: TODO: convert_type_post for atomic types\n");
		return 0;
	}
	(void)target_typ;
	switch (emu_typ->typ) {
	case TYPE_BUILTIN: return 1;
	case TYPE_ARRAY: return 1;
	case TYPE_STRUCT_UNION:
		if (!emu_typ->is_validated || emu_typ->is_incomplete) {
			printf("Error: incomplete structure for %s\n", string_content(obj_name));
			return 0;
		}
		// Hard coded
		if (!string_add_char(dest, 'p')) {
			printf("Error: failed to add type char for very large structure return as parameter\n");
			return 0;
		}
		return 2;
	case TYPE_ENUM: return 1;
	case TYPE_PTR: return 1;
	case TYPE_FUNCTION: return 1;
	}
	printf("Error: convert_type_post on unknown type %u\n", emu_typ->typ);
	return 0;
}

int solve_request(request_t *req, type_t *emu_typ, type_t *target_typ, khash_t(conv_map) *conv_map) {
	if (emu_typ->typ != target_typ->typ) {
		printf("Error: %s: emulated and target types are different (emulated is %u, target is %u)\n",
			string_content(req->obj_name), emu_typ->typ, target_typ->typ);
		return 0;
	}
	if (emu_typ->typ == TYPE_FUNCTION) {
		int needs_D = 0, needs_my = req->def.fun.typ && (req->def.rty == RQT_FUN_MY), needs_2 = 0;
		int convert_post;
		size_t idx_conv;
		req->val.fun.typ = string_new();
		if (!req->val.fun.typ) {
			printf("Error: failed to create function type string\n");
			return 0;
		}
		if (!convert_type(req->val.fun.typ, emu_typ->val.fun.ret, target_typ->val.fun.ret, 0, &req->val.fun.needs_S, &needs_D, &needs_my, conv_map, req->obj_name))
			goto fun_fail;
		idx_conv = string_len(req->val.fun.typ);
		if (!string_add_char(req->val.fun.typ, 'F')) {
			printf("Error: failed to add convention char\n");
			goto fun_fail;
		}
		convert_post = convert_type_post(req->val.fun.typ, emu_typ->val.fun.ret, target_typ->val.fun.ret, req->obj_name);
		if (!convert_post) goto fun_fail;
		if (emu_typ->val.fun.nargs == (size_t)-1) {
			printf("Warning: %s: assuming empty specification is void specification\n", string_content(req->obj_name));
			if (convert_post == 1) {
				if (!string_add_char(req->val.fun.typ, 'v')) {
					printf("Error: failed to add void specification char\n");
					goto fun_fail;
				}
			}
		} else if (!emu_typ->val.fun.nargs && !emu_typ->val.fun.has_varargs) {
			if (convert_post == 1) {
				if (!string_add_char(req->val.fun.typ, 'v')) {
					printf("Error: failed to add void specification char\n");
					goto fun_fail;
				}
			}
		} else {
			for (size_t i = 0; i < emu_typ->val.fun.nargs; ++i) {
				if (!convert_type(req->val.fun.typ, emu_typ->val.fun.args[i], target_typ->val.fun.args[i], 1, NULL, &needs_D, &needs_my, conv_map, req->obj_name))
					goto fun_fail;
			}
			if (emu_typ->val.fun.has_varargs) {
				if (req->def.fun.typ
				      && (string_len(req->def.fun.typ) == string_len(req->val.fun.typ) + 1)
				      && !strncmp(string_content(req->def.fun.typ), string_content(req->val.fun.typ), string_len(req->val.fun.typ))
				      && ((string_content(req->def.fun.typ)[string_len(req->val.fun.typ)] == 'M')
				       || (string_content(req->def.fun.typ)[string_len(req->val.fun.typ)] == 'N'))) {
					if (!string_add_char(req->val.fun.typ, string_content(req->def.fun.typ)[string_len(req->val.fun.typ)])) {
						printf("Error: failed to add type char '%c' for %s\n",
							string_content(req->def.fun.typ)[string_len(req->val.fun.typ)],
							builtin2str[emu_typ->val.builtin]);
						goto fun_fail;
					}
				} else {
					needs_my = 1;
					if (!string_add_char(req->val.fun.typ, 'V')) {
						printf("Error: failed to add type char 'V' for %s\n", builtin2str[emu_typ->val.builtin]);
						goto fun_fail;
					}
				}
			}
		}
		
	// fun_succ:
		// Add 'E' by default, unless we have the same function as before
		if (needs_my && (req->default_comment
		                  || (req->def.rty != RQT_FUN_MY)
		                  || strcmp(string_content(req->def.fun.typ), string_content(req->val.fun.typ)))) {
			if (!string_add_char_at(req->val.fun.typ, 'E', idx_conv + 1)) {
				printf("Error: failed to add emu char\n");
				goto fun_fail;
			}
		}
		if (req->def.fun.typ && (req->def.rty == RQT_FUN_2) && !needs_my) {
			needs_2 = 1;
			req->val.fun.fun2 = string_dup(req->def.fun.fun2);
			if (!req->val.fun.fun2) {
				printf("Error: failed to duplicate string (request for function %s with default redirection)\n", string_content(req->obj_name));
				return 0;
			}
		} else if (req->def.fun.typ && (req->def.rty == RQT_FUN_D) && !needs_my) {
			needs_2 = 0;
			req->val.fun.fun2 = string_dup(req->def.fun.fun2);
			if (!req->val.fun.fun2) {
				printf("Error: failed to duplicate string (request for function %s with long double types)\n", string_content(req->obj_name));
				return 0;
			}
		} else if (!needs_my && needs_D) {
			req->val.fun.fun2 = string_new();
			if (!req->val.fun.fun2) {
				printf("Error: failed to create empty string (request for function %s with long double types)\n", string_content(req->obj_name));
				return 0;
			}
		}
		req->val.rty =
			needs_my ? RQT_FUN_MY :
			needs_2 ? RQT_FUN_2 :
			needs_D ? RQT_FUN_D : RQT_FUN;
		req->has_val = 1;
		return 1;
		
	fun_fail:
		string_del(req->val.fun.typ);
		return 0;
	} else {
		int needs_D = 0, needs_my = req->def.dat.has_size && (req->def.rty == RQT_DATAM);
		switch (get_safeness(emu_typ, target_typ, &needs_D, &needs_my, conv_map, req->obj_name)) {
		case SAFE_EXPAND:
			needs_my = 1;
			/* FALLTHROUGH */
		case SAFE_OK:
			req->val.rty = needs_my ? RQT_DATAM : (IS_RQT_FUNCTION(req->def.rty) ? RQT_DATA : req->def.rty);
			req->val.dat.has_size = 1;
			req->val.dat.sz = emu_typ->szinfo.size;
			req->has_val = 1;
			return 1;
			
		case SAFE_ABORT:
		default:
			log_TODO_nopos("solve_request for data %s with non-simple type ", string_content(req->obj_name));
			type_print(emu_typ);
			printf("\n");
			return 0;
		}
	}
}
int solve_request_map(request_t *req, khash_t(decl_map) *emu_decl_map, khash_t(decl_map) *target_decl_map, khash_t(conv_map) *conv_map) {
	int hasemu = 0, hastarget = 0;
	khiter_t emuit, targetit;
	emuit = kh_get(decl_map, emu_decl_map, string_content(req->obj_name));
	if (emuit == kh_end(emu_decl_map)) {
		goto failed;
	}
	if ((kh_val(emu_decl_map, emuit)->storage == STORAGE_STATIC) || (kh_val(emu_decl_map, emuit)->storage == STORAGE_TLS_STATIC)) {
		goto failed;
	}
	hasemu = 1;
	targetit = kh_get(decl_map, target_decl_map, string_content(req->obj_name));
	if (targetit == kh_end(target_decl_map)) {
		goto failed;
	}
	if ((kh_val(target_decl_map, targetit)->storage == STORAGE_STATIC) || (kh_val(target_decl_map, targetit)->storage == STORAGE_TLS_STATIC)) {
		goto failed;
	}
	hastarget = 1;
	return solve_request(req, kh_val(emu_decl_map, emuit)->typ, kh_val(target_decl_map, targetit)->typ, conv_map);
	
failed:
	if (string_content(req->obj_name)[0] != '_') {
		if (!hasemu && !hastarget) {
			printf("Error: %s was not declared in the emulated and target architectures\n", string_content(req->obj_name));
		} else if (!hasemu) {
			printf("Error: %s was not declared only in the emulated architecture\n", string_content(req->obj_name));
		} else if (!hastarget) {
			printf("Error: %s was not declared only in the target architecture\n", string_content(req->obj_name));
		} else {
			printf("Error: internal error: failed but found for %s\n", string_content(req->obj_name));
		}
	}
	return 0;
}
int solve_references(VECTOR(references) *refs, khash_t(decl_map) *emu_decl_map, khash_t(decl_map) *target_decl_map, khash_t(conv_map) *conv_map) {
	int ret = 1;
	int cond_depth = 0, ok_depth = 0;
	vector_for(references, ref, refs) {
		switch (ref->typ) {
		case REF_REQ:
			if (ok_depth == cond_depth) {
				if (!solve_request_map(&ref->req, emu_decl_map, target_decl_map, conv_map)) ret = 0;
			} else {
				ref->req.ignored = 1;
			}
			break;
		case REF_LINE:
			break;
		case REF_IFDEF:
			++cond_depth;
			break;
		case REF_IFNDEF:
			if (cond_depth == ok_depth) ++ok_depth;
			++cond_depth;
			break;
		case REF_ELSE:
			if (cond_depth == ok_depth) --ok_depth;
			else if (cond_depth == ok_depth + 1) ++ok_depth;
			break;
		case REF_ENDIF:
			if (cond_depth == ok_depth) --ok_depth;
			--cond_depth;
			break;
		}
	}
	return ret;
}