summaryrefslogtreecommitdiff
path: root/GenC.cs
blob: 43a1bf9f5151338618c701c874ffcc6d27720df9 (plain)
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
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
// GenC.cs - C code generator
//
// Copyright (C) 2011-2022  Piotr Fusik
//
// This file is part of CiTo, see https://github.com/pfusik/cito
//
// CiTo is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// CiTo is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with CiTo.  If not, see http://www.gnu.org/licenses/

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace Foxoft.Ci
{

public class GenC : GenCCpp
{
	bool StringAssign;
	bool StringSubstring;
	bool StringAppend;
	bool StringIndexOf;
	bool StringLastIndexOf;
	bool StringEndsWith;
	bool StringFormat;
	bool MatchFind;
	bool MatchPos;
	bool PtrConstruct;
	bool SharedMake;
	bool SharedAddRef;
	bool SharedRelease;
	bool SharedAssign;
	readonly SortedDictionary<string, string> ListFrees = new SortedDictionary<string, string>();
	bool TreeCompareInteger;
	bool TreeCompareString;
	readonly SortedSet<TypeCode> Compares = new SortedSet<TypeCode>();
	readonly SortedSet<TypeCode> Contains = new SortedSet<TypeCode>();
	readonly List<CiExpr> CurrentTemporaries = new List<CiExpr>(); // CiExpr or CiType
	readonly List<CiVar> VarsToDestruct = new List<CiVar>();
	protected CiClass CurrentClass;

	protected override void WriteSelfDoc(CiMethod method)
	{
		if (method.CallType == CiCallType.Static)
			return;
		Write(" * @param self This <code>");
		WriteName(method.Parent);
		WriteLine("</code>.");
	}

	protected override void IncludeStdInt()
	{
		Include("stdint.h");
	}

	protected override void IncludeAssert()
	{
		Include("assert.h");
	}

	protected override void IncludeMath()
	{
		Include("math.h");
	}

	protected virtual void IncludeStdBool()
	{
		Include("stdbool.h");
	}

	public override void VisitLiteralNull()
	{
		Write("NULL");
	}

	protected override void WritePrintfWidth(CiInterpolatedPart part)
	{
		base.WritePrintfWidth(part);
		if (IsStringSubstring(part.Argument, out bool _, out CiExpr _, out CiExpr _, out CiExpr _)) {
			Trace.Assert(part.Precision < 0);
			Write(".*");
		}
	}

	protected override void WriteInterpolatedStringArg(CiExpr expr)
	{
		if (IsStringSubstring(expr, out bool cast, out CiExpr ptr, out CiExpr offset, out CiExpr length)) {
			length.Accept(this, CiPriority.Argument);
			Write(", ");
			if (cast)
				Write("(const char *) ");
			WriteArrayPtrAdd(ptr, offset);
		}
		else
			base.WriteInterpolatedStringArg(expr);
	}

	public override CiExpr Visit(CiInterpolatedString expr, CiPriority parent)
	{
		Include("stdarg.h");
		Include("stdio.h");
		this.StringFormat = true;
		Write("CiString_Format(");
		WritePrintf(expr, false);
		return expr;
	}

	protected virtual void WriteCamelCaseNotKeyword(string name)
	{
		switch (name) {
		case "this":
			Write("self");
			break;
		case "Asm":
		case "Assert":
		case "Auto":
		case "Bool":
		case "Break":
		case "Byte":
		case "Case":
		case "Char":
		case "Class":
		case "Const":
		case "Continue":
		case "Default":
		case "Do":
		case "Double":
		case "Else":
		case "Enum":
		case "Extern":
		case "False":
		case "Float":
		case "For":
		case "Foreach":
		case "Goto":
		case "If":
		case "Inline":
		case "Int":
		case "Long":
		case "Register":
		case "Restrict":
		case "Return":
		case "Short":
		case "Signed":
		case "Sizeof":
		case "Static":
		case "Struct":
		case "Switch":
		case "True":
		case "Typedef":
		case "Typeof": // gcc extension
		case "Union":
		case "Unsigned":
		case "Void":
		case "Volatile":
		case "While":
		case "asm":
		case "auto":
		case "char":
		case "extern":
		case "goto":
		case "inline":
		case "register":
		case "restrict":
		case "signed":
		case "sizeof":
		case "struct":
		case "typedef":
		case "typeof": // gcc extension
		case "union":
		case "unsigned":
		case "volatile":
			WriteCamelCase(name);
			Write('_');
			break;
		default:
			WriteCamelCase(name);
			break;
		}
	}

	protected override void WriteName(CiSymbol symbol)
	{
		switch (symbol) {
		case CiContainerType _:
			Write(this.Namespace);
			Write(symbol.Name);
			break;
		case CiMethod _:
			Write(this.Namespace);
			Write(symbol.Parent.Name);
			Write('_');
			Write(symbol.Name);
			break;
		case CiConst _:
			if (symbol.Parent is CiContainerType) {
				Write(this.Namespace);
				Write(symbol.Parent.Name);
				Write('_');
			}
			WriteUppercaseWithUnderscores(symbol.Name);
			break;
		default:
			WriteCamelCaseNotKeyword(symbol.Name);
			break;
		}
	}

	void WriteSelfForField(CiClass fieldClass)
	{
		Write("self->");
		for (CiClass klass = this.CurrentClass; klass != fieldClass; klass = (CiClass) klass.Parent)
			Write("base.");
	}

	protected override void WriteLocalName(CiSymbol symbol, CiPriority parent)
	{
		if (symbol.Parent is CiForeach forEach && forEach.Collection.Type is CiArrayType array) {
			if (array is CiListType) {
				if (parent == CiPriority.Primary)
					Write('(');
				Write('*');
				WriteCamelCaseNotKeyword(symbol.Name);
				if (parent == CiPriority.Primary)
					Write(')');
			}
			else if (array.ElementType is CiClass klass) {
				if (parent > CiPriority.Add)
					Write('(');
				forEach.Collection.Accept(this, CiPriority.Add);
				Write(" + ");
				WriteCamelCaseNotKeyword(symbol.Name);
				if (parent > CiPriority.Add)
					Write(')');
			}
			else {
				forEach.Collection.Accept(this, CiPriority.Primary);
				Write('[');
				WriteCamelCaseNotKeyword(symbol.Name);
				Write(']');
			}
			return;
		}
		if (symbol is CiField)
			WriteSelfForField((CiClass) symbol.Parent);
		WriteName(symbol);
	}

	void WriteMatchProperty(CiSymbolReference expr, int which)
	{
		this.MatchPos = true;
		Write("CiMatch_GetPos(");
		expr.Left.Accept(this, CiPriority.Argument);
		Write(", ");
		VisitLiteralLong(which);
		Write(')');
	}

	static bool IsDictionaryClassStgIndexing(CiExpr expr)
	{
		return expr is CiBinaryExpr indexing
			&& indexing.Op == CiToken.LeftBracket
			&& indexing.Left.Type is CiDictionaryType dict
			&& dict.ValueType is CiClass;
	}

	public override CiExpr Visit(CiSymbolReference expr, CiPriority parent)
	{
		if (expr.Left == null || expr.Symbol is CiConst)
			WriteLocalName(expr.Symbol, parent);
		else if (expr.Symbol == CiSystem.CollectionCount) {
			switch (expr.Left.Type) {
			case CiListType _:
			case CiStackType _:
				expr.Left.Accept(this, CiPriority.Primary);
				Write("->len");
				break;
			case CiSortedDictionaryType _:
				WriteCall("g_tree_nnodes", expr.Left);
				break;
			case CiHashSetType _:
			case CiDictionaryType _:
				WriteCall("g_hash_table_size", expr.Left);
				break;
			default:
				throw new NotImplementedException(expr.Left.Type.ToString());
			}
		}
		else if (expr.Symbol == CiSystem.MatchStart)
			WriteMatchProperty(expr, 0);
		else if (expr.Symbol == CiSystem.MatchEnd)
			WriteMatchProperty(expr, 1);
		else if (expr.Symbol == CiSystem.MatchLength)
			WriteMatchProperty(expr, 2);
		else if (expr.Symbol == CiSystem.MatchValue) {
			Write("g_match_info_fetch(");
			expr.Left.Accept(this, CiPriority.Argument);
			Write(", 0)");
		}
		else if (IsDictionaryClassStgIndexing(expr.Left)) {
			expr.Left.Accept(this, CiPriority.Primary);
			Write("->");
			WriteName(expr.Symbol);
		}
		else
			return base.Visit(expr, parent);
		return expr;
	}

	void WriteGlib(string s)
	{
		Include("glib.h");
		Write(s);
	}

	protected virtual void WriteStringPtrType()
	{
		Write("const char *");
	}

	void WriteArrayPrefix(CiType type)
	{
		if (type is CiArrayType array) {
			WriteArrayPrefix(array.ElementType);
			if (type is CiArrayPtrType arrayPtr) {
				if (array.ElementType is CiArrayStorageType)
					Write('(');
				switch (arrayPtr.Modifier) {
				case CiToken.EndOfFile:
					Write("const *");
					break;
				case CiToken.ExclamationMark:
				case CiToken.Hash:
					Write('*');
					break;
				default:
					throw new NotImplementedException(arrayPtr.Modifier.ToString());
				}
			}
		}
	}

	void WriteDefinition(CiType type, Action symbol, bool promote, bool space)
	{
		if (type is CiListType) {
			WriteGlib("GArray *");
			symbol();
			return;
		}
		CiType baseType = type.BaseType;
		switch (baseType) {
		case CiIntegerType integer:
			Write(GetIntegerTypeCode(integer, promote && type == baseType));
			if (space)
				Write(' ');
			break;
		case CiStringPtrType _:
			WriteStringPtrType();
			break;
		case CiStringStorageType _:
			Write("char *");
			break;
		case CiClassPtrType classPtr:
			if (classPtr.Modifier == CiToken.EndOfFile)
				Write("const ");
			if (classPtr.Class == CiSystem.RegexClass)
				WriteGlib("GRegex");
			else if (classPtr.Class == CiSystem.MatchClass)
				WriteGlib("GMatchInfo");
			else
				WriteName(classPtr.Class);
			Write(" *");
			break;
		case CiStackType _:
			WriteGlib("GArray *");
			break;
		case CiHashSetType _:
			WriteGlib("GHashTable *");
			break;
		case CiSortedDictionaryType _:
			WriteGlib("GTree *");
			break;
		case CiDictionaryType _:
			WriteGlib("GHashTable *");
			break;
		case CiContainerType _:
			if (baseType == CiSystem.BoolType) {
				IncludeStdBool();
				Write("bool");
			}
			else if (baseType == CiSystem.MatchClass) {
				WriteGlib("GMatchInfo *");
				space = false;
			}
			else if (baseType == CiSystem.LockClass) {
				Include("threads.h");
				Write("mtx_t");
			}
			else
				WriteName(baseType);
			if (space)
				Write(' ');
			break;
		default:
			Write(baseType.Name);
			if (space)
				Write(' ');
			break;
		}
		WriteArrayPrefix(type);
		symbol();
		while (type is CiArrayType array) {
			if (type is CiArrayStorageType arrayStorage) {
				Write('[');
				VisitLiteralLong(arrayStorage.Length);
				Write(']');
			}
			else if (array.ElementType is CiArrayStorageType)
				Write(')');
			type = array.ElementType;
		}
	}

	void WriteSignature(CiMethod method, Action symbol)
	{
		if (method.Type == CiSystem.VoidType && method.Throws) {
			IncludeStdBool();
			Write("bool ");
			symbol();
		}
		else
			WriteDefinition(method.Type, symbol, true, true);
	}

	protected override void Write(CiType type, bool promote)
	{
		WriteDefinition(type, () => {}, promote, type is CiArrayPtrType);
	}

	protected override void WriteTypeAndName(CiNamedValue value)
	{
		WriteDefinition(value.Type, () => WriteName(value), true, true);
	}

	void WriteXstructorPtr(bool need, CiClass klass, string name)
	{
		if (need) {
			Write("(CiMethodPtr) ");
			WriteName(klass);
			Write('_');
			Write(name);
		}
		else
			Write("NULL");
	}

	void WriteDynamicArrayCast(CiType elementType)
	{
		Write('(');
		WriteDefinition(elementType, () => Write(elementType is CiArrayType ? "(*)" : "*"), false, true);
		Write(") ");
	}

	protected override void WriteNewArray(CiType elementType, CiExpr lengthExpr, CiPriority parent)
	{
		this.SharedMake = true;
		if (parent > CiPriority.Mul)
			Write('(');
		WriteDynamicArrayCast(elementType);
		Write("CiShared_Make(");
		if (lengthExpr != null)
			lengthExpr.Accept(this, CiPriority.Argument);
		else
			Write('1');
		Write(", sizeof(");
		Write(elementType, false);
		Write("), ");
		if (elementType == CiSystem.StringStorageType) {
			this.PtrConstruct = true;
			Write("(CiMethodPtr) CiPtr_Construct, free");
		}
		else if (elementType.IsDynamicPtr) {
			this.PtrConstruct = true;
			this.SharedRelease = true;
			Write("(CiMethodPtr) CiPtr_Construct, CiShared_Release");
		}
		else if (elementType is CiClass klass) {
			WriteXstructorPtr(NeedsConstructor(klass), klass, "Construct");
			Write(", ");
			WriteXstructorPtr(NeedsDestructor(klass), klass, "Destruct");
		}
		else
			Write("NULL, NULL");
		Write(')');
		if (parent > CiPriority.Mul)
			Write(')');
	}

	protected override void WriteNew(CiClass klass, CiPriority parent)
	{
		WriteNewArray(klass, null, parent);
	}

	void WriteStringStorageValue(CiExpr expr)
	{
		if (IsStringSubstring(expr, out bool cast, out CiExpr ptr, out CiExpr offset, out CiExpr length)) {
			Include("string.h");
			this.StringSubstring = true;
			Write("CiString_Substring(");
			if (cast)
				Write("(const char *) ");
			WriteArrayPtrAdd(ptr, offset);
			Write(", ");
			length.Accept(this, CiPriority.Argument);
			Write(')');
		}
		else if (expr is CiInterpolatedString
				|| (expr is CiCallExpr call && expr.Type == CiSystem.StringStorageType && !call.Method.IsReferenceTo(CiSystem.StringSubstring)))
			expr.Accept(this, CiPriority.Argument);
		else {
			Include("string.h");
			WriteCall("strdup", expr);
		}
	}

	protected override void WriteArrayStorageInit(CiArrayStorageType array, CiExpr value)
	{
		switch (value) {
		case null:
			if (array.StorageType == CiSystem.StringStorageType || array.StorageType.IsDynamicPtr)
				Write(" = { NULL }");
			break;
		case CiLiteral literal when literal.IsDefaultValue:
			Write(" = { ");
			literal.Accept(this, CiPriority.Argument);
			Write(" }");
			break;
		default:
			throw new NotImplementedException("Only null, zero and false supported");
		}
	}

	string GetListDestroy(CiType type)
	{
		if (!(type is CiListType || type is CiStackType))
			return null;
		CiType elementType = ((CiCollectionType) type).ElementType;
		if (elementType == CiSystem.StringStorageType) {
			this.ListFrees["String"] = "free(*(void **) ptr)";
			return "CiList_FreeString";
		}
		if (elementType.IsDynamicPtr) {
			this.ListFrees["Shared"] = "CiShared_Release(*(void **) ptr)";
			return "CiList_FreeShared";
		}
		if (elementType is CiClass klass && NeedsDestructor(klass))
			return $"(GDestroyNotify) {klass.Name}_Destruct";
		if (elementType is CiListType || elementType is CiStackType) {
			this.ListFrees["List"] = "g_array_free(*(GArray **) ptr, TRUE)";
			return "CiList_FreeList";
		}
		if (elementType is CiDictionaryType) {
			if (elementType is CiSortedDictionaryType) {
				this.ListFrees["SortedDictionary"] = "g_tree_unref(*(GTree **) ptr)";
				return "CiList_FreeSortedDictionary";
			}
			this.ListFrees["Dictionary"] = "g_hash_table_unref(*(GHashTable **) ptr)";
			return "CiList_FreeDictionary";
		}
		return null;
	}

	string GetDictionaryDestroy(CiType type)
	{
		if (type == CiSystem.StringStorageType || type is CiArrayStorageType)
			return "free";
		if (type.IsDynamicPtr) {
			this.SharedRelease = true;
			return "CiShared_Release";
		}
		if (type is CiClass klass)
			return NeedsDestructor(klass) ? $"(GDestroyNotify) {klass.Name}_Delete" /* TODO: emit */ : "free";
		if (type is CiListType)
			return "(GDestroyNotify) g_array_unref";
		if (type is CiDictionaryType)
			return type is CiSortedDictionaryType ? "(GDestroyNotify) g_tree_unref" : "(GDestroyNotify) g_hash_table_unref";
		return "NULL";
	}

	void WriteHashEqual(CiType keyType)
	{
		Write(keyType is CiStringType ? "g_str_hash, g_str_equal" : "NULL, NULL");
	}

	void WriteNewHashTable(CiType keyType, string valueDestroy)
	{
		Write("g_hash_table_new");
		string keyDestroy = GetDictionaryDestroy(keyType);
		if (keyDestroy == "NULL" && valueDestroy == "NULL") {
			Write('(');
			WriteHashEqual(keyType);
		}
		else {
			Write("_full(");
			WriteHashEqual(keyType);
			Write(", ");
			Write(keyDestroy);
			Write(", ");
			Write(valueDestroy);
		}
		Write(')');
	}

	protected override void WriteNewStorage(CiType type)
	{
		switch (type) {
		case CiListType _:
		case CiStackType _:
			Write("g_array_new(FALSE, FALSE, sizeof(");
			Write(((CiCollectionType) type).ElementType, false);
			Write("))");
			break;
		case CiHashSetType set:
			WriteNewHashTable(set.ElementType, "NULL");
			break;
		case CiSortedDictionaryType dict:
			string valueDestroy = GetDictionaryDestroy(dict.ValueType);
			if (dict.KeyType == CiSystem.StringPtrType && valueDestroy == "NULL")
				Write("g_tree_new((GCompareFunc) strcmp");
			else {
				Write("g_tree_new_full(CiTree_Compare");
				switch (dict.KeyType) {
				case CiIntegerType _:
					this.TreeCompareInteger = true;
					Write("Integer");
					break;
				case CiStringType _:
					this.TreeCompareString = true;
					Write("String");
					break;
				default:
					throw new NotImplementedException(dict.KeyType.ToString());
				}
				Write(", NULL, ");
				Write(GetDictionaryDestroy(dict.KeyType));
				Write(", ");
				Write(valueDestroy);
			}
			Write(')');
			break;
		case CiDictionaryType dict:
			WriteNewHashTable(dict.KeyType, GetDictionaryDestroy(dict.ValueType));
			break;
		default:
			base.WriteNewStorage(type);
			break;
		}
	}

	protected override void WriteVarInit(CiNamedValue def)
	{
		if (def.Value == null && (def.Type == CiSystem.StringStorageType || def.Type.IsDynamicPtr))
			Write(" = NULL");
		else
			base.WriteVarInit(def);
	}

	int WriteTemporary(CiType type, CiExpr expr)
	{
		bool assign = expr != null || type is CiListType || type is CiDictionaryType;
		int id = this.CurrentTemporaries.IndexOf(type);
		if (id < 0) {
			id = this.CurrentTemporaries.Count;
			WriteDefinition(type, () => { Write("citemp"); VisitLiteralLong(id); }, false, true);
			if (assign) {
				Write(" = ");
				if (expr != null)
					WriteCoerced(type, expr, CiPriority.Argument);
				else
					WriteNewStorage(type);
			}
			WriteLine(';');
			this.CurrentTemporaries.Add(expr);
		}
		else if (assign) {
			Write("citemp");
			VisitLiteralLong(id);
			Write(" = ");
			if (expr != null)
				WriteCoerced(type, expr, CiPriority.Argument);
			else
				WriteNewStorage(type);
			WriteLine(';');
			this.CurrentTemporaries[id] = expr;
		}
		return id;
	}

	void WriteStorageTemporary(CiExpr expr)
	{
		if (expr is CiCallExpr && expr.Type is CiClass)
			WriteTemporary(expr.Type, expr);
	}

	void WriteTemporaries(CiExpr expr)
	{
		switch (expr) {
		case CiVar def:
			if (def.Value != null)
				WriteTemporaries(def.Value);
			break;
		case CiLiteral _:
			break;
		case CiInterpolatedString interp:
			foreach (CiInterpolatedPart part in interp.Parts)
				WriteTemporaries(part.Argument);
			break;
		case CiSymbolReference symbol:
			if (symbol.Left != null)
				WriteTemporaries(symbol.Left);
			break;
		case CiUnaryExpr unary:
			if (unary.Inner != null) // new C()
				WriteTemporaries(unary.Inner);
			break;
		case CiBinaryExpr binary:
			WriteTemporaries(binary.Left);
			WriteTemporaries(binary.Right);
			break;
		case CiSelectExpr select:
			WriteTemporaries(select.Cond);
			break;
		case CiCallExpr call:
			if (call.Method.Left != null) {
				WriteTemporaries(call.Method.Left);
				WriteStorageTemporary(call.Method.Left);
			}
			int i = 0;
			foreach (CiVar param in ((CiMethod) call.Method.Symbol).Parameters) {
				if (i >= call.Arguments.Length)
					break;
				CiExpr arg = call.Arguments[i++];
				WriteTemporaries(arg);
				if (param.Type is CiClassPtrType)
					WriteStorageTemporary(arg);
			}
			break;
		default:
			throw new NotImplementedException(expr.GetType().Name);
		}
	}

	static bool IsTemporary(CiExpr expr) => expr is CiCallExpr && expr.Type is CiClass;

	static bool HasTemporaries(CiExpr expr)
	{
		switch (expr) {
		case CiLiteral _:
		case CiSymbol _:
			return false;
		case CiInterpolatedString interp:
			foreach (CiInterpolatedPart part in interp.Parts)
				if (HasTemporaries(part.Argument))
					return true;
			return false;
		case CiSymbolReference symbol:
			return symbol.Left != null && HasTemporaries(symbol.Left);
		case CiUnaryExpr unary:
			return unary.Inner != null && HasTemporaries(unary.Inner);
		case CiBinaryExpr binary:
			return HasTemporaries(binary.Left) || HasTemporaries(binary.Right);
		case CiSelectExpr select:
			return HasTemporaries(select.Cond);
		case CiCallExpr call:
			if (call.Method.Left != null) {
				if (call.Method.Left.Type is CiListType && (call.Method.Name == "Add" || call.Method.Name == "Insert"))
					return true;
				if (call.Method.Left.Type is CiStackType && call.Method.Name == "Push")
					return true;
				if (IsTemporary(call.Method.Left) || HasTemporaries(call.Method.Left))
					return true;
			}
			int i = 0;
			foreach (CiVar param in ((CiMethod) call.Method.Symbol).Parameters) {
				if (i >= call.Arguments.Length)
					break;
				CiExpr arg = call.Arguments[i++];
				if (HasTemporaries(arg) || (param.Type is CiClassPtrType && IsTemporary(arg)))
					return true;
			}
			return false;
		default:
			throw new NotImplementedException(expr.GetType().Name);
		}
	}

	void CleanupTemporaries()
	{
		for (int i = 0; i < this.CurrentTemporaries.Count; i++) {
			if (!(this.CurrentTemporaries[i] is CiType))
				this.CurrentTemporaries[i] = this.CurrentTemporaries[i].Type;
		}
	}

	static bool NeedToDestruct(CiSymbol symbol)
	{
		CiType type = symbol.Type;
		while (type is CiArrayStorageType array)
			type = array.ElementType;
		return type == CiSystem.StringStorageType
			|| type.IsDynamicPtr
			|| type is CiListType
			|| type is CiDictionaryType
			|| (type is CiClass klass && (klass == CiSystem.MatchClass || klass == CiSystem.LockClass || NeedsDestructor(klass)));
	}

	protected override void WriteVar(CiNamedValue def)
	{
		base.WriteVar(def);
		if (NeedToDestruct(def))
			this.VarsToDestruct.Add((CiVar) def);
	}

	void WriteGPointerCast(CiType type, CiExpr expr)
	{
		if (type is CiNumericType || type is CiEnum) {
			Write("GINT_TO_POINTER(");
			expr.Accept(this, CiPriority.Argument);
			Write(')');
		}
		else if (type == CiSystem.StringPtrType && expr.Type == CiSystem.StringPtrType) {
			Write("(gpointer) ");
			expr.Accept(this, CiPriority.Primary);
		}
		else
			WriteCoerced(type, expr, CiPriority.Argument);
	}

	void WriteGConstPointerCast(CiExpr expr)
	{
		switch (expr.Type) {
		case CiStringType _:
		case CiClassPtrType _:
		case CiArrayPtrType _:
			expr.Accept(this, CiPriority.Argument);
			break;
		default:
			Write("(gconstpointer) ");
			expr.Accept(this, CiPriority.Primary);
			break;
		}
	}

	void StartDictionaryInsert(CiExpr dict, CiExpr key)
	{
		Write(dict.Type is CiSortedDictionaryType ? "g_tree_insert(" : "g_hash_table_insert(");
		dict.Accept(this, CiPriority.Argument);
		Write(", ");
		WriteGPointerCast(((CiDictionaryType) dict.Type).KeyType, key);
		Write(", ");
	}

	protected override void WriteAssign(CiBinaryExpr expr, CiPriority parent)
	{
		if (expr.Left is CiBinaryExpr indexing
		 && indexing.Op == CiToken.LeftBracket
		 && indexing.Left.Type is CiDictionaryType dict) {
			StartDictionaryInsert(indexing.Left, indexing.Right);
			WriteGPointerCast(dict.ValueType, expr.Right);
			Write(')');
		}
		else if (expr.Left.Type == CiSystem.StringStorageType) {
			if (parent == CiPriority.Statement
			 && IsTrimSubstring(expr) is CiExpr length) {
				WriteIndexing(expr.Left, length);
				Write(" = '\\0'");
			}
			else {
				this.StringAssign = true;
				Write("CiString_Assign(&");
				expr.Left.Accept(this, CiPriority.Primary);
				Write(", ");
				WriteStringStorageValue(expr.Right);
				Write(')');
			}
		}
		else if (expr.Left.Type.IsDynamicPtr) {
			if (expr.Left.Type.IsClass(CiSystem.RegexClass)) {
				// TODO: only if previously assigned non-null
				// Write("g_regex_unref(");
				// expr.Left.Accept(this, CiPriority.Argument);
				// WriteLine(");");
				base.WriteAssign(expr, parent);
			}
			else {
				this.SharedAssign = true;
				Write("CiShared_Assign((void **) &");
				expr.Left.Accept(this, CiPriority.Primary);
				Write(", ");
				if (expr.Right is CiSymbolReference) {
					this.SharedAddRef = true;
					Write("CiShared_AddRef(");
					expr.Right.Accept(this, CiPriority.Argument);
					Write(')');
				}
				else
					expr.Right.Accept(this, CiPriority.Argument);
				Write(')');
			}
		}
		else
			base.WriteAssign(expr, parent);
	}

	protected override bool HasInitCode(CiNamedValue def)
	{
		return (def is CiField && (def.Value != null || def.Type.StorageType == CiSystem.StringStorageType || def.Type.IsDynamicPtr || def.Type is CiListType || def.Type is CiDictionaryType))
			|| GetThrowingMethod(def.Value) != null
			|| (def.Type.StorageType is CiClass klass && (klass == CiSystem.LockClass || NeedsConstructor(klass)))
			|| GetListDestroy(def.Type) != null;
	}

	protected override void WriteInitCode(CiNamedValue def)
	{
		if (!HasInitCode(def))
			return;
		CiType type = def.Type;
		int nesting = 0;
		while (type is CiArrayStorageType array) {
			OpenLoop("int", nesting++, array.Length);
			type = array.ElementType;
		}
		if (type is CiClass klass) {
			if (klass == CiSystem.LockClass) {
				Write("mtx_init(&");
				WriteArrayElement(def, nesting);
				WriteLine(", mtx_plain | mtx_recursive);");
			}
			else if (NeedsConstructor(klass)) {
				WriteName(klass);
				Write("_Construct(&");
				WriteArrayElement(def, nesting);
				WriteLine(");");
			}
		}
		else {
			if (def is CiField) {
				WriteArrayElement(def, nesting);
				if (nesting > 0) {
					Write(" = ");
					if (type == CiSystem.StringStorageType || type.IsDynamicPtr)
						Write("NULL");
					else
						def.Value.Accept(this, CiPriority.Argument);
				}
				else
					WriteVarInit(def);
				WriteLine(';');
			}
			CiMethod throwingMethod = GetThrowingMethod(def.Value);
			if (throwingMethod != null)
				WriteForwardThrow(parent => WriteArrayElement(def, nesting), throwingMethod);
		}
		if (GetListDestroy(type) is string destroy) {
			Write("g_array_set_clear_func(");
			WriteArrayElement(def, nesting);
			Write(", ");
			Write(destroy);
			WriteLine(");");
		}
		while (--nesting >= 0)
			CloseBlock();
	}

	void WriteMemberAccess(CiExpr left, CiClass symbolClass)
	{
		if (left.Type is CiClass klass)
			Write('.');
		else {
			Write("->");
			klass = ((CiClassPtrType) left.Type).Class;
		}
		for (; klass != symbolClass; klass = (CiClass) klass.Parent)
			Write("base.");
	}

	protected override void WriteMemberOp(CiExpr left, CiSymbolReference symbol)
	{
		WriteMemberAccess(left, (CiClass) symbol.Symbol.Parent);
	}

	protected override void WriteArrayPtr(CiExpr expr, CiPriority parent)
	{
		if (expr.Type is CiListType list) {
			Write('(');
			Write(list.ElementType, false);
			Write(" *) ");
			expr.Accept(this, CiPriority.Primary);
			Write("->data");
		}
		else
			expr.Accept(this, parent);
	}

	void WriteClassPtr(CiClass resultClass, CiExpr expr, CiPriority parent)
	{
		if (expr.Type is CiClass klass && klass != CiSystem.MatchClass && !IsDictionaryClassStgIndexing(expr)) {
			Write('&');
			int tempId = this.CurrentTemporaries.IndexOf(expr);
			if (tempId >= 0) {
				Write("citemp");
				VisitLiteralLong(tempId);
			}
			else
				expr.Accept(this, CiPriority.Primary);
		}
		else if (expr.Type is CiClassPtrType klassPtr && klassPtr.Class != resultClass) {
			Write('&');
			expr.Accept(this, CiPriority.Primary);
			Write("->base");
			klass = (CiClass) klassPtr.Class.Parent;
		}
		else {
			expr.Accept(this, parent);
			return;
		}
		for (; klass != resultClass; klass = (CiClass) klass.Parent)
			Write(".base");
	}

	protected override void WriteCoercedInternal(CiType type, CiExpr expr, CiPriority parent)
	{
		if (type == CiSystem.StringStorageType)
			WriteStringStorageValue(expr);
		else if (type is CiClassPtrType resultPtr) {
			if (resultPtr.Modifier == CiToken.Hash && expr is CiSymbolReference && parent != CiPriority.Equality) {
				this.SharedAddRef = true;
				Write('(');
				WriteName(resultPtr.Class);
				WriteCall(" *) CiShared_AddRef", expr);
			}
			else
				WriteClassPtr(resultPtr.Class, expr, parent);
		}
		else if (type is CiArrayPtrType arrayPtr && arrayPtr.Modifier == CiToken.Hash && expr is CiSymbolReference && parent != CiPriority.Equality) {
			this.SharedAddRef = true;
			WriteDynamicArrayCast(arrayPtr.ElementType);
			WriteCall("CiShared_AddRef", expr);
		}
		else
			base.WriteCoercedInternal(type, expr, parent);
	}

	protected virtual void WriteSubstringEqual(bool cast, CiExpr ptr, CiExpr offset, string literal, CiPriority parent, bool not)
	{
		if (parent > CiPriority.Equality)
			Write('(');
		Include("string.h");
		Write("memcmp(");
		WriteArrayPtrAdd(ptr, offset);
		Write(", ");
		VisitLiteralString(literal);
		Write(", ");
		VisitLiteralLong(literal.Length);
		Write(')');
		Write(GetEqOp(not));
		Write('0');
		if (parent > CiPriority.Equality)
			Write(')');
	}

	protected virtual void WriteEqualStringInternal(CiExpr left, CiExpr right, CiPriority parent, bool not)
	{
		if (parent > CiPriority.Equality)
			Write('(');
		Include("string.h");
		WriteCall("strcmp", left, right);
		Write(GetEqOp(not));
		Write('0');
		if (parent > CiPriority.Equality)
			Write(')');
	}

	protected override void WriteEqualString(CiExpr left, CiExpr right, CiPriority parent, bool not)
	{
		if (IsStringSubstring(left, out bool cast, out CiExpr ptr, out CiExpr offset, out CiExpr lengthExpr)
		 && right is CiLiteralString literal) {
			string rightValue = literal.Value;
			if (lengthExpr is CiLiteralLong leftLength) {
				if (leftLength.Value != rightValue.Length)
					throw new NotImplementedException(); // TODO: evaluate compile-time
				WriteSubstringEqual(cast, ptr, offset, rightValue, parent, not);
			}
			else if (not) {
				if (parent > CiPriority.CondOr)
					Write('(');
				lengthExpr.Accept(this, CiPriority.Equality);
				Write(" != ");
				VisitLiteralLong(rightValue.Length);
				Write(" || ");
				WriteSubstringEqual(cast, ptr, offset, rightValue, CiPriority.CondOr, true);
				if (parent > CiPriority.CondOr)
					Write(')');
			}
			else {
				if (parent > CiPriority.CondAnd || parent == CiPriority.CondOr)
					Write('(');
				lengthExpr.Accept(this, CiPriority.Equality);
				Write(" == ");
				VisitLiteralLong(rightValue.Length);
				Write(" && ");
				WriteSubstringEqual(cast, ptr, offset, rightValue, CiPriority.CondAnd, false);
				if (parent > CiPriority.CondAnd || parent == CiPriority.CondOr)
					Write(')');
			}
		}
		else
			WriteEqualStringInternal(left, right, parent, not);
	}

	protected override void WriteEqual(CiBinaryExpr expr, CiPriority parent, bool not)
	{
		if (expr.Left.Type is CiStringType && expr.Right.Type is CiStringType)
			WriteEqualString(expr.Left, expr.Right, parent, not);
		else
			base.WriteEqual(expr, parent, not);
	}

	protected override void WriteStringLength(CiExpr expr)
	{
		Include("string.h");
		WriteCall("(int) strlen", expr);
	}

	void WriteStringMethod(string name, CiExpr obj, CiExpr[] args)
	{
		Include("string.h");
		Write("CiString_");
		WriteCall(name, obj, args[0]);
	}

	void WriteSizeofCompare(CiArrayType array)
	{
		Write(", sizeof(");
		TypeCode typeCode = GetTypeCode(array.ElementType, false);
		Write(typeCode);
		Write("), CiCompare_");
		Write(typeCode);
		Write(')');
		this.Compares.Add(typeCode);
	}

	protected void WriteArrayFill(CiExpr obj, CiExpr[] args)
	{
		Write("for (int _i = 0; _i < ");
		if (args.Length == 1)
			VisitLiteralLong(((CiArrayStorageType) obj.Type).Length);
		else
			args[2].Accept(this, CiPriority.Rel); // FIXME: side effect in every iteration
		WriteLine("; _i++)");
		Write('\t');
		obj.Accept(this, CiPriority.Primary); // FIXME: side effect in every iteration
		Write('[');
		if (args.Length > 1 && !args[1].IsLiteralZero) {
			args[1].Accept(this, CiPriority.Add); // FIXME: side effect in every iteration
			Write(" + ");
		}
		Write("_i] = ");
		args[0].Accept(this, CiPriority.Argument); // FIXME: side effect in every iteration
	}

	void WriteListAddInsert(CiExpr obj, bool insert, string function, CiExpr[] args)
	{
		CiType elementType = ((CiCollectionType) obj.Type).ElementType;
		// TODO: don't emit temporary variable if already a var/field of matching type - beware of integer promotions!
		int id = WriteTemporary(elementType, elementType.IsFinal ? null : args[args.Length - 1]);
		if (elementType is CiClass klass && NeedsConstructor(klass)) {
			WriteName(klass);
			Write("_Construct(&citemp");
			VisitLiteralLong(id);
			WriteLine(");");
		}
		Write(function);
		Write('(');
		obj.Accept(this, CiPriority.Argument);
		if (insert) {
			Write(", ");
			args[0].Accept(this, CiPriority.Argument);
		}
		Write(", citemp");
		VisitLiteralLong(id);
		Write(')');
		this.CurrentTemporaries[id] = elementType;
	}

	void WriteDictionaryLookup(CiExpr obj, string function, CiExpr key)
	{
		Write(function);
		Write('(');
		obj.Accept(this, CiPriority.Argument);
		Write(", ");
		WriteGConstPointerCast(key);
		Write(')');
	}

	void WriteArgsAndRightParenthesis(CiMethod method, CiExpr[] args)
	{
		int i = 0;
		foreach (CiVar param in method.Parameters) {
			if (i > 0 || method.CallType != CiCallType.Static)
				Write(", ");
			if (i >= args.Length)
				param.Value.Accept(this, CiPriority.Argument);
			else
				WriteCoerced(param.Type, args[i], CiPriority.Argument);
			i++;
		}
		Write(')');
	}

	void WriteRegexOptions(CiExpr[] args)
	{
		if (!WriteRegexOptions(args, "", " | ", "", "G_REGEX_CASELESS", "G_REGEX_MULTILINE", "G_REGEX_DOTALL"))
			Write('0');
	}

	void WriteConsoleWrite(CiExpr obj, CiExpr[] args, bool newLine)
	{
		bool error = obj.IsReferenceTo(CiSystem.ConsoleError);
		Include("stdio.h");
		if (args.Length == 0)
			Write(error ? "putc('\\n', stderr)" : "putchar('\\n')");
		else if (args[0] is CiInterpolatedString interpolated) {
			Write(error ? "fprintf(stderr, " : "printf(");
			WritePrintf(interpolated, newLine);
		}
		else if (args[0].Type is CiNumericType) {
			Write(error ? "fprintf(stderr, " : "printf(");
			Write(args[0].Type is CiIntegerType ? "\"%d" : "\"%g");
			if (newLine)
				Write("\\n");
			Write("\", ");
			args[0].Accept(this, CiPriority.Argument);
			Write(')');
		}
		else if (!newLine) {
			Write("fputs(");
			args[0].Accept(this, CiPriority.Argument);
			Write(error ? ", stderr)" : ", stdout)");
		}
		else if (error) {
			if (args[0] is CiLiteralString literal) {
				Write("fputs(");
				WriteStringLiteralWithNewLine(literal.Value);
				Write(", stderr)");
			}
			else {
				Write("fprintf(stderr, \"%s\\n\", ");
				args[0].Accept(this, CiPriority.Argument);
				Write(')');
			}
		}
		else
			WriteCall("puts", args[0]);
	}

	protected void WriteCCall(CiExpr obj, CiMethod method, CiExpr[] args)
	{
		if (obj != null && obj.IsReferenceTo(CiSystem.BasePtr)) {
			WriteName(method);
			Write("(&self->base");
		}
		else {
			CiClass klass = this.CurrentClass;
			CiClass definingClass = (CiClass) method.Parent;
			CiClass declaringClass = definingClass;
			switch (method.CallType) {
			case CiCallType.Override:
				declaringClass = (CiClass) method.DeclaringMethod.Parent;
				goto case CiCallType.Abstract;
			case CiCallType.Abstract:
			case CiCallType.Virtual:
				if (obj != null)
					klass = obj.Type as CiClass ?? ((CiClassPtrType) obj.Type).Class;
				CiClass ptrClass = GetVtblPtrClass(klass);
				CiClass structClass = GetVtblStructClass(definingClass);
				if (structClass != ptrClass) {
					Write("((const ");
					WriteName(structClass);
					Write("Vtbl *) ");
				}
				if (obj != null) {
					obj.Accept(this, CiPriority.Primary);
					WriteMemberAccess(obj, ptrClass);
				}
				else
					WriteSelfForField(ptrClass);
				Write("vtbl");
				if (structClass != ptrClass)
					Write(')');
				Write("->");
				WriteCamelCase(method.Name);
				break;
			default:
				WriteName(method);
				break;
			}
			Write('(');
			if (method.CallType != CiCallType.Static) {
				if (obj != null)
					WriteClassPtr(declaringClass, obj, CiPriority.Argument);
				else if (klass == declaringClass)
					Write("self");
				else {
					Write("&self->base");
					for (klass = (CiClass) klass.Parent; klass != declaringClass; klass = (CiClass) klass.Parent)
						Write(".base");
				}
			}
		}
		WriteArgsAndRightParenthesis(method, args);
	}

	void WriteListAdd(CiExpr obj, CiExpr[] args)
	{
		CiType elementType = ((CiCollectionType) obj.Type).ElementType;
		if (elementType is CiArrayStorageType || (elementType is CiClass klass && !NeedsConstructor(klass))) {
			Write("g_array_set_size(");
			obj.Accept(this, CiPriority.Argument);
			Write(", ");
			obj.Accept(this, CiPriority.Primary); // TODO: side effect
			Write("->len + 1)");
		}
		else
			WriteListAddInsert(obj, false, "g_array_append_val", args);
	}

	protected override void WriteCall(CiExpr obj, CiMethod method, CiExpr[] args, CiPriority parent)
	{
		if (obj == null)
			WriteCCall(null, method, args);
		else if (method == CiSystem.StringContains) {
			Include("string.h");
			if (parent > CiPriority.Equality)
				Write('(');
			if (IsOneAsciiString(args[0], out char c)) {
				Write("strchr(");
				obj.Accept(this, CiPriority.Argument);
				Write(", ");
				WriteCharLiteral(c);
				Write(')');
			}
			else
				WriteCall("strstr", obj, args[0]);
			Write(" != NULL");
			if (parent > CiPriority.Equality)
				Write(')');
		}
		else if (method == CiSystem.StringIndexOf) {
			this.StringIndexOf = true;
			WriteStringMethod("IndexOf", obj, args);
		}
		else if (method == CiSystem.StringLastIndexOf) {
			this.StringLastIndexOf = true;
			WriteStringMethod("LastIndexOf", obj, args);
		}
		else if (method == CiSystem.StringStartsWith) {
			if (parent > CiPriority.Equality)
				Write('(');
			if (IsOneAsciiString(args[0], out char c)) {
				obj.Accept(this, CiPriority.Primary);
				Write("[0] == ");
				WriteCharLiteral(c);
			}
			else {
				Include("string.h");
				Write("strncmp(");
				obj.Accept(this, CiPriority.Argument);
				Write(", ");
				args[0].Accept(this, CiPriority.Argument);
				Write(", strlen(");
				args[0].Accept(this, CiPriority.Argument); // TODO: side effect
				Write(")) == 0");
			}
			if (parent > CiPriority.Equality)
				Write(')');
		}
		else if (method == CiSystem.StringEndsWith) {
			this.StringEndsWith = true;
			WriteStringMethod("EndsWith", obj, args);
		}
		else if (method == CiSystem.StringSubstring && args.Length == 1) {
			if (parent > CiPriority.Add)
				Write('(');
			obj.Accept(this, CiPriority.Add);
			Write(" + ");
			args[0].Accept(this, CiPriority.Add);
			if (parent > CiPriority.Add)
				Write(')');
		}
		else if (obj.Type is CiArrayType array && method.Name == "BinarySearch") {
			if (parent > CiPriority.Add)
				Write('(');
			Write("(const ");
			Write(array.ElementType, false);
			Write(" *) bsearch(&");
			args[0].Accept(this, CiPriority.Primary); // TODO: not lvalue, promoted
			Write(", ");
			if (args.Length == 1)
				WriteArrayPtr(obj, CiPriority.Argument);
			else
				WriteArrayPtrAdd(obj, args[1]);
			Write(", ");
			if (args.Length == 1)
				VisitLiteralLong(((CiArrayStorageType) array).Length);
			else
				args[2].Accept(this, CiPriority.Primary);
			WriteSizeofCompare(array);
			Write(" - ");
			WriteArrayPtr(obj, CiPriority.Mul);
			if (parent > CiPriority.Add)
				Write(')');
		}
		else if (obj.Type is CiArrayType array2 && method.Name == "CopyTo") {
			Include("string.h");
			Write("memcpy(");
			WriteArrayPtrAdd(args[1], args[2]);
			Write(", ");
			WriteArrayPtrAdd(obj, args[0]);
			Write(", ");
			if (array2.ElementType is CiRangeType range
			 && ((range.Min >= 0 && range.Max <= byte.MaxValue)
				|| (range.Min >= sbyte.MinValue && range.Max <= sbyte.MaxValue)))
				args[3].Accept(this, CiPriority.Argument);
			else {
				args[3].Accept(this, CiPriority.Mul);
				Write(" * sizeof(");
				Write(array2.ElementType, false);
				Write(')');
			}
			Write(')');
		}
		else if (obj.Type is CiArrayType array3 && method.Name == "Fill") {
			if (args[0] is CiLiteral literal && literal.IsDefaultValue) {
				Include("string.h");
				Write("memset(");
				if (args.Length == 1) {
					obj.Accept(this, CiPriority.Argument);
					Write(", 0, sizeof(");
					obj.Accept(this, CiPriority.Argument);
					Write(')');
				}
				else {
					WriteArrayPtrAdd(obj, args[1]);
					Write(", 0, ");
					args[2].Accept(this, CiPriority.Mul);
					Write(" * sizeof(");
					Write(array3.ElementType, false);
					Write(')');
				}
				Write(')');
			}
			else
				WriteArrayFill(obj, args);
		}
		else if (method == CiSystem.CollectionSortAll) {
			TypeCode typeCode = GetTypeCode(((CiArrayType) obj.Type).ElementType, false);
			if (obj.Type is CiArrayStorageType arrayStorage) {
				Write("qsort(");
				WriteArrayPtr(obj, CiPriority.Argument);
				Write(", ");
				VisitLiteralLong(arrayStorage.Length);
				Write(", sizeof(");
				Write(typeCode);
				Write(')');
			}
			else {
				Write("g_array_sort(");
				obj.Accept(this, CiPriority.Argument);
			}
			Write(", CiCompare_");
			Write(typeCode);
			Write(')');
			this.Compares.Add(typeCode);
		}
		else if (method == CiSystem.CollectionSortPart) {
			Write("qsort(");
			WriteArrayPtrAdd(obj, args[0]);
			Write(", ");
			args[1].Accept(this, CiPriority.Primary);
			WriteSizeofCompare((CiArrayType) obj.Type);
		}
		else if (obj.Type is CiListType && method.Name == "Add")
			WriteListAdd(obj, args);
		else if (obj.Type is CiListType list && method.Name == "Contains") {
			Write("CiArray_Contains_");
			TypeCode typeCode = GetTypeCode(list.ElementType, false);
			if (typeCode == TypeCode.String) {
				Include("string.h");
				Write("string((const char * const");
			}
			else {
				Write(typeCode);
				Write("((const ");
				Write(typeCode);
			}
			Write(" *) ");
			obj.Accept(this, CiPriority.Primary);
			Write("->data, ");
			obj.Accept(this, CiPriority.Primary); // TODO: side effect
			Write("->len, ");
			args[0].Accept(this, CiPriority.Argument);
			Write(')');
			this.Contains.Add(typeCode);
		}
		else if (method == CiSystem.CollectionClear) {
			switch (obj.Type) {
			case CiListType _:
			case CiStackType _:
				Write("g_array_set_size(");
				obj.Accept(this, CiPriority.Argument);
				Write(", 0)");
				break;
			case CiSortedDictionaryType _:
				// TODO: since glib-2.70: WriteCall("g_tree_remove_all", obj);
				Write("g_tree_destroy(g_tree_ref(");
				obj.Accept(this, CiPriority.Argument);
				Write("))");
				break;
			case CiHashSetType _:
			case CiDictionaryType _:
				WriteCall("g_hash_table_remove_all", obj);
				break;
			default:
				throw new NotImplementedException(obj.Type.ToString());
			}
		}
		else if (obj.Type is CiListType && method.Name == "Insert")
			WriteListAddInsert(obj, true, "g_array_insert_val", args);
		else if (method == CiSystem.ListRemoveAt)
			WriteCall("g_array_remove_index", obj, args[0]);
		else if (method == CiSystem.ListRemoveRange)
			WriteCall("g_array_remove_range", obj, args[0], args[1]);
		else if (obj.Type is CiStackType && method.Name == "Peek") { 
			StartArrayIndexing(obj);
			obj.Accept(this, CiPriority.Primary); // TODO: side effect
			Write("->len - 1)");
		}
		else if (obj.Type is CiStackType && method.Name == "Pop") { 
			// FIXME: destroy
			StartArrayIndexing(obj);
			Write("--");
			obj.Accept(this, CiPriority.Primary); // TODO: side effect
			Write("->len)");
		}
		else if (obj.Type is CiStackType && method.Name == "Push")
			WriteListAdd(obj, args);
		else if (obj.Type is CiHashSetType set && method.Name == "Add") {
			Write("g_hash_table_add(");
			obj.Accept(this, CiPriority.Argument);
			Write(", ");
			WriteGPointerCast(set.ElementType, args[0]);
			Write(')');
		}
		else if (obj.Type is CiHashSetType && method.Name == "Contains")
			WriteDictionaryLookup(obj, "g_hash_table_contains", args[0]);
		else if ((obj.Type is CiHashSetType || obj.Type is CiDictionaryType) && method.Name == "Remove")
			WriteDictionaryLookup(obj, obj.Type is CiSortedDictionaryType ? "g_tree_remove" : "g_hash_table_remove", args[0]);
		else if (obj.Type is CiDictionaryType dict && method.Name == "Add") {
			StartDictionaryInsert(obj, args[0]);
			switch (dict.ValueType) {
			case CiListType _:
			case CiDictionaryType _:
				WriteNewStorage(dict.ValueType);
				break;
			case CiClass klass when klass.IsPublic && klass.Constructor != null && klass.Constructor.Visibility == CiVisibility.Public:
				WriteName(klass);
				Write("_New()");
				break;
			default:
				Write("malloc(sizeof(");
				Write(dict.ValueType, false);
				Write("))");
				break;
			}
			Write(')');
		}
		else if (obj.Type is CiDictionaryType && method.Name == "ContainsKey") {
			if (obj.Type is CiSortedDictionaryType) {
				Write("g_tree_lookup_extended(");
				obj.Accept(this, CiPriority.Argument);
				Write(", ");
				WriteGConstPointerCast(args[0]);
				Write(", NULL, NULL)");
			}
			else
				WriteDictionaryLookup(obj, "g_hash_table_contains", args[0]);
		}
		else if (method == CiSystem.UTF8GetByteCount)
			WriteStringLength(args[0]);
		else if (method == CiSystem.UTF8GetBytes) {
			Include("string.h");
			Write("memcpy("); // NOT strcpy because without the NUL terminator
			WriteArrayPtrAdd(args[1], args[2]);
			Write(", ");
			args[0].Accept(this, CiPriority.Argument);
			Write(", strlen(");
			args[0].Accept(this, CiPriority.Argument); // FIXME: side effect
			Write("))");
		}
		else if (method == CiSystem.RegexCompile) {
			WriteGlib("g_regex_new(");
			args[0].Accept(this, CiPriority.Argument);
			Write(", ");
			WriteRegexOptions(args);
			Write(", 0, NULL)");
		}
		else if (method == CiSystem.RegexEscape) {
			WriteGlib("g_regex_escape_string(");
			args[0].Accept(this, CiPriority.Argument);
			Write(", -1)");
		}
		else if (method == CiSystem.RegexIsMatchStr) {
			WriteGlib("g_regex_match_simple(");
			args[1].Accept(this, CiPriority.Argument);
			Write(", ");
			args[0].Accept(this, CiPriority.Argument);
			Write(", ");
			WriteRegexOptions(args);
			Write(", 0)");
		}
		else if (method == CiSystem.RegexIsMatchRegex) {
			Write("g_regex_match(");
			obj.Accept(this, CiPriority.Argument);
			Write(", ");
			args[0].Accept(this, CiPriority.Argument);
			Write(", 0, NULL)");
		}
		else if (method == CiSystem.MatchFindStr) {
			this.MatchFind = true;
			Write("CiMatch_Find(&");
			obj.Accept(this, CiPriority.Primary);
			Write(", ");
			args[0].Accept(this, CiPriority.Argument);
			Write(", ");
			args[1].Accept(this, CiPriority.Argument);
			Write(", ");
			WriteRegexOptions(args);
			Write(')');
		}
		else if (method == CiSystem.MatchFindRegex) {
			Write("g_regex_match(");
			args[1].Accept(this, CiPriority.Argument);
			Write(", ");
			args[0].Accept(this, CiPriority.Argument);
			Write(", 0, &");
			obj.Accept(this, CiPriority.Primary);
			Write(')');
		}
		else if (method == CiSystem.MatchGetCapture)
			WriteCall("g_match_info_fetch", obj, args[0]);
		else if (method == CiSystem.ConsoleWrite)
			WriteConsoleWrite(obj, args, false);
		else if (method == CiSystem.ConsoleWriteLine)
			WriteConsoleWrite(obj, args, true);
		else if (method == CiSystem.EnvironmentGetEnvironmentVariable)
			WriteCall("getenv", args[0]);
		else if (obj.IsReferenceTo(CiSystem.MathClass)) {
			Include("math.h");
			WriteMathCall(method, args);
		}
		else
			WriteCCall(obj, method, args);
	}

	void StartArrayIndexing(CiExpr obj)
	{
		Write("g_array_index(");
		obj.Accept(this, CiPriority.Argument);
		Write(", ");
		Write(((CiCollectionType) obj.Type).ElementType, false);
		Write(", ");
	}

	protected override void WriteIndexing(CiBinaryExpr expr, CiPriority parent)
	{
		switch (expr.Left.Type) {
		case CiListType list:
			if (list.ElementType is CiArrayStorageType) {
				Write('(');
				WriteDynamicArrayCast(list.ElementType);
				expr.Left.Accept(this, CiPriority.Primary);
				Write("->data)[");
				expr.Right.Accept(this, CiPriority.Argument);
				Write(']');
			}
			else {
				StartArrayIndexing(expr.Left);
				expr.Right.Accept(this, CiPriority.Argument);
				Write(')');
			}
			break;
		case CiDictionaryType dict:
			string function = dict is CiSortedDictionaryType ? "g_tree_lookup" : "g_hash_table_lookup";
			if (dict.ValueType is CiIntegerType && dict.ValueType != CiSystem.LongType) {
				Write("GPOINTER_TO_INT(");
				WriteDictionaryLookup(expr.Left, function, expr.Right);
				Write(')');
			}
			else {
				if (parent > CiPriority.Mul)
					Write('(');
				if (dict.ValueType is CiClass || dict.ValueType is CiArrayStorageType)
					WriteDynamicArrayCast(dict.ValueType);
				else {
					Write('(');
					Write(dict.ValueType, false);
					Write(") ");
					if (dict.ValueType is CiEnum) {
						Trace.Assert(parent <= CiPriority.Mul, "Should close two parens");
						Write("GPOINTER_TO_INT(");
					}
				}
				WriteDictionaryLookup(expr.Left, function, expr.Right);
				if (parent > CiPriority.Mul || dict.ValueType is CiEnum)
					Write(')');
			}
			break;
		default:
			base.WriteIndexing(expr, parent);
			break;
		}
	}

	public override CiExpr Visit(CiBinaryExpr expr, CiPriority parent)
	{
		switch (expr.Op) {
		case CiToken.Equal:
		case CiToken.NotEqual:
		case CiToken.Greater:
			if (IsStringEmpty(expr, out CiExpr str)) {
				str.Accept(this, CiPriority.Primary);
				Write(expr.Op == CiToken.Equal ? "[0] == '\\0'" : "[0] != '\\0'");
				return expr;
			}
			break;
		case CiToken.AddAssign:
			if (expr.Left.Type == CiSystem.StringStorageType) {
				if (expr.Right is CiInterpolatedString rightInterpolated) {
					this.StringAssign = true;
					Write("CiString_Assign(&");
					expr.Left.Accept(this, CiPriority.Primary);
					Write(", ");
					CiInterpolatedPart[] parts = new CiInterpolatedPart[1 + rightInterpolated.Parts.Length];
					parts[0] = new CiInterpolatedPart("", expr.Left); // TODO: side effect
					rightInterpolated.Parts.CopyTo(parts, 1);
					Visit(new CiInterpolatedString(parts, rightInterpolated.Suffix), CiPriority.Argument);
				}
				else {
					Include("string.h");
					this.StringAppend = true;
					Write("CiString_Append(&");
					expr.Left.Accept(this, CiPriority.Primary);
					Write(", ");
					expr.Right.Accept(this, CiPriority.Argument);
				}
				Write(')');
				return expr;
			}
			break;
		default:
			break;
		}

		return base.Visit(expr, parent);
	}

	protected override void WriteResource(string name, int length)
	{
		Write("CiResource_");
		foreach (char c in name)
			Write(CiLexer.IsLetterOrDigit(c) ? c : '_');
	}

	static CiMethod GetThrowingMethod(CiExpr expr)
	{
		switch (expr) {
		case CiBinaryExpr binary when binary.Op == CiToken.Assign:
			return GetThrowingMethod(binary.Right);
		case CiCallExpr call:
			CiMethod method = (CiMethod) call.Method.Symbol;
			return method.Throws ? method : null;
		default:
			return null;
		}
	}

	void WriteForwardThrow(Action<CiPriority> source, CiMethod throwingMethod)
	{
		Write("if (");
		if (throwingMethod.Type is CiNumericType) {
			if (throwingMethod.Type is CiIntegerType) {
				source(CiPriority.Equality);
				Write(" == -1");
			}
			else {
				IncludeMath();
				Write("isnan(");
				source(CiPriority.Argument);
				Write(')');
			}
		}
		else if (throwingMethod.Type == CiSystem.VoidType) {
			Write('!');
			source(CiPriority.Primary);
		}
		else {
			source(CiPriority.Equality);
			Write(" == NULL");
		}
		Write(')');
		if (this.VarsToDestruct.Count > 0) {
			Write(' ');
			OpenBlock();
			Visit((CiThrow) null);
			CloseBlock();
		}
		else {
			WriteLine();
			this.Indent++;
			Visit((CiThrow) null);
			this.Indent--;
		}
	}

	void WriteDestruct(CiSymbol symbol)
	{
		if (!NeedToDestruct(symbol))
			return;
		CiType type = symbol.Type;
		int nesting = 0;
		while (type is CiArrayStorageType array) {
			Write("for (int _i");
			VisitLiteralLong(nesting);
			Write(" = ");
			VisitLiteralLong(array.Length - 1);
			Write("; _i");
			VisitLiteralLong(nesting);
			Write(" >= 0; _i");
			VisitLiteralLong(nesting);
			WriteLine("--)");
			this.Indent++;
			nesting++;
			type = array.ElementType;
		}
		if (type is CiClass klass) {
			if (klass == CiSystem.MatchClass)
				Write("g_match_info_free(");
			else if (klass == CiSystem.LockClass)
				Write("mtx_destroy(&");
			else {
				WriteName(klass);
				Write("_Destruct(&");
			}
		}
		else if (type.IsDynamicPtr) {
			if (type.IsClass(CiSystem.RegexClass))
				Write("g_regex_unref(");
			else {
				this.SharedRelease = true;
				Write("CiShared_Release(");
			}
		}
		else if (type is CiListType)
			Write("g_array_free(");
		else if (type is CiDictionaryType)
			Write(type is CiSortedDictionaryType ? "g_tree_unref(" : "g_hash_table_unref(");
		else
			Write("free(");
		WriteLocalName(symbol, CiPriority.Primary);
		for (int i = 0; i < nesting; i++) {
			Write("[_i");
			VisitLiteralLong(i);
			Write(']');
		}
		if (type is CiListType)
			Write(", TRUE");
		WriteLine(");");
		this.Indent -= nesting;
	}

	void WriteDestructAll(CiSymbol exceptSymbol = null)
	{
		for (int i = this.VarsToDestruct.Count; --i >= 0; ) {
			CiSymbol symbol = this.VarsToDestruct[i];
			if (symbol != exceptSymbol)
				WriteDestruct(symbol);
		}
	}

	void WriteDestructLoopOrSwitch(CiCondCompletionStatement loopOrSwitch)
	{
		for (int i = this.VarsToDestruct.Count; --i >= 0; ) {
			CiVar def = this.VarsToDestruct[i];
			if (!loopOrSwitch.Encloses(def))
				break;
			WriteDestruct(def);
		}
	}

	void TrimVarsToDestruct(int i)
	{
		this.VarsToDestruct.RemoveRange(i, this.VarsToDestruct.Count - i);
	}

	public override void Visit(CiBlock statement)
	{
		OpenBlock();
		int temporariesCount = this.CurrentTemporaries.Count;
		Write(statement.Statements);
		int i = this.VarsToDestruct.Count;
		for (; i > 0; i--) {
			CiVar def = this.VarsToDestruct[i - 1];
			if (def.Parent != statement) // destroy only the variables in this block
				break;
			if (statement.CompletesNormally)
				WriteDestruct(def);
		}
		TrimVarsToDestruct(i);
		this.CurrentTemporaries.RemoveRange(temporariesCount, this.CurrentTemporaries.Count - temporariesCount);
		CloseBlock();
	}

	bool BreakOrContinueNeedsBlock(CiCondCompletionStatement loopOrSwitch)
	{
		int count = this.VarsToDestruct.Count;
		return count > 0 && loopOrSwitch.Encloses(this.VarsToDestruct[count - 1]);
	}

	bool NeedsBlock(CiStatement statement)
	{
		switch (statement) {
		case CiExpr expr:
			return HasTemporaries(expr) || GetThrowingMethod(expr) != null;
		case CiBreak brk:
			return BreakOrContinueNeedsBlock(brk.LoopOrSwitch);
		case CiContinue cont:
			return BreakOrContinueNeedsBlock(cont.Loop);
		case CiReturn ret:
			return this.VarsToDestruct.Count > 0 || (ret.Value != null && HasTemporaries(ret.Value));
		case CiThrow _:
			return this.VarsToDestruct.Count > 0;
		default:
			return false;
		}
	}

	protected override void WriteChild(CiStatement statement)
	{
		if (NeedsBlock(statement)) {
			Write(' ');
			OpenBlock();
			statement.Accept(this);
			CloseBlock();
		}
		else
			base.WriteChild(statement);
	}

	public override void Visit(CiBreak statement)
	{
		WriteDestructLoopOrSwitch(statement.LoopOrSwitch);
		base.Visit(statement);
	}

	public override void Visit(CiContinue statement)
	{
		WriteDestructLoopOrSwitch(statement.Loop);
		base.Visit(statement);
	}

	public override void Visit(CiExpr statement)
	{
		WriteTemporaries(statement);
		CiMethod throwingMethod = GetThrowingMethod(statement);
		if (throwingMethod != null)
			WriteForwardThrow(parent => statement.Accept(this, parent), throwingMethod);
		else if (statement is CiCallExpr && statement.Type == CiSystem.StringStorageType) {
			Write("free(");
			statement.Accept(this, CiPriority.Argument);
			WriteLine(");");
		}
		else if (statement is CiCallExpr && statement.Type != CiSystem.VoidType && statement.Type.IsDynamicPtr) {
			this.SharedRelease = true;
			Write("CiShared_Release(");
			statement.Accept(this, CiPriority.Argument);
			WriteLine(");");
		}
		else
			base.Visit(statement);
		CleanupTemporaries();
	}

	void StartForeachHashTable(CiForeach statement)
	{
		OpenBlock();
		WriteLine("GHashTableIter cidictit;");
		Write("g_hash_table_iter_init(&cidictit, ");
		statement.Collection.Accept(this, CiPriority.Argument);
		WriteLine(");");
	}

	void WriteDictIterVar(CiNamedValue iter, string value)
	{
		WriteTypeAndName(iter);
		Write(" = ");
		if (iter.Type is CiIntegerType && iter.Type != CiSystem.LongType) {
			Write("GPOINTER_TO_INT(");
			Write(value);
			Write(')');
		}
		else {
			Write('(');
			Write(iter.Type, false);
			Write(") ");
			Write(value);
		}
		WriteLine(';');
	}

	public override void Visit(CiForeach statement)
	{
		string element = statement.Element.Name;
		switch (statement.Collection.Type) {
		case CiArrayStorageType array:
			Write("for (int ");
			WriteCamelCaseNotKeyword(element);
			Write(" = 0; ");
			WriteCamelCaseNotKeyword(element);
			Write(" < ");
			VisitLiteralLong(array.Length);
			Write("; ");
			WriteCamelCaseNotKeyword(element);
			Write("++)");
			WriteChild(statement.Body);
			break;
		case CiListType list:
			Write("for (");
			CiType elementType = list.ElementType;
			Write(elementType, false);
			Write(" const *");
			WriteCamelCaseNotKeyword(element);
			Write(" = (");
			Write(elementType, false);
			Write(" const *) ");
			statement.Collection.Accept(this, CiPriority.Primary);
			Write("->data, ");
			for (; elementType is CiArrayType array; elementType = array.ElementType)
				Write('*');
			if (elementType is CiStringType || elementType is CiClassPtrType)
				Write("* const ");
			Write("*ciend = ");
			WriteCamelCaseNotKeyword(element);
			Write(" + ");
			statement.Collection.Accept(this, CiPriority.Primary); // TODO: side effect
			Write("->len; ");
			WriteCamelCaseNotKeyword(element);
			Write(" < ciend; ");
			WriteCamelCaseNotKeyword(element);
			Write("++)");
			WriteChild(statement.Body);
			break;
		case CiHashSetType set:
			StartForeachHashTable(statement);
			WriteLine("gpointer cikey;");
			Write("while (g_hash_table_iter_next(&cidictit, &cikey, NULL)) ");
			OpenBlock();
			WriteDictIterVar(statement.Element, "cikey");
			FlattenBlock(statement.Body);
			CloseBlock();
			CloseBlock();
			break;
		case CiSortedDictionaryType dict:
			Write("for (GTreeNode *cidictit = g_tree_node_first(");
			statement.Collection.Accept(this, CiPriority.Argument);
			Write("); cidictit != NULL; cidictit = g_tree_node_next(cidictit)) ");
			OpenBlock();
			WriteDictIterVar(statement.Element, "g_tree_node_key(cidictit)");
			WriteDictIterVar(statement.ValueVar, "g_tree_node_value(cidictit)");
			FlattenBlock(statement.Body);
			CloseBlock();
			break;
		case CiDictionaryType dict:
			StartForeachHashTable(statement);
			WriteLine("gpointer cikey, civalue;");
			Write("while (g_hash_table_iter_next(&cidictit, &cikey, &civalue)) ");
			OpenBlock();
			WriteDictIterVar(statement.Element, "cikey");
			WriteDictIterVar(statement.ValueVar, "civalue");
			FlattenBlock(statement.Body);
			CloseBlock();
			CloseBlock();
			break;
		default:
			throw new NotImplementedException(statement.Collection.Type.ToString());
		}
	}

	public override void Visit(CiLock statement)
	{
		Write("mtx_lock(&");
		statement.Lock.Accept(this, CiPriority.Primary);
		WriteLine(");");
		// TODO
		statement.Body.Accept(this);
		Write("mtx_unlock(&");
		statement.Lock.Accept(this, CiPriority.Primary);
		WriteLine(");");
	}

	public override void Visit(CiReturn statement)
	{
		if (statement.Value == null) {
			WriteDestructAll();
			WriteLine(this.CurrentMethod.Throws ? "return true;" : "return;");
		}
		else if (this.VarsToDestruct.Count == 0 || statement.Value is CiLiteral) {
			WriteDestructAll();
			WriteTemporaries(statement.Value);
			base.Visit(statement);
		}
		else {
			if (statement.Value is CiSymbolReference symbol) {
				if (this.VarsToDestruct.Contains(symbol.Symbol)) {
					// Optimization: avoid copy
					WriteDestructAll(symbol.Symbol);
					Write("return ");
					if (this.CurrentMethod.Type is CiClassPtrType resultPtr)
						WriteClassPtr(resultPtr.Class, symbol, CiPriority.Argument); // upcast, but don't AddRef
					else
						symbol.Accept(this, CiPriority.Argument);
					WriteLine(';');
					return;
				}
				if (symbol.Left == null) {
					// Local variable value doesn't depend on destructed variables
					WriteDestructAll();
					base.Visit(statement);
					return;
				}
			}
			WriteTemporaries(statement.Value);
			WriteDefinition(this.CurrentMethod.Type, () => Write("returnValue"), true, true);
			Write(" = ");
			WriteCoerced(this.CurrentMethod.Type, statement.Value, CiPriority.Argument);
			WriteLine(';');
			WriteDestructAll();
			WriteLine("return returnValue;");
		}
	}

	protected override void WriteCaseBody(CiStatement[] statements)
	{
		if (statements[0] is CiVar
		 || (statements[0] is CiConst konst && konst.Type is CiArrayType))
			WriteLine(';');
		int varsToDestructCount = this.VarsToDestruct.Count;
		Write(statements);
		TrimVarsToDestruct(varsToDestructCount);
	}

	void WriteThrowReturnValue()
	{
		if (this.CurrentMethod.Type is CiNumericType) {
			if (this.CurrentMethod.Type is CiIntegerType)
				Write("-1");
			else {
				IncludeMath();
				Write("NAN");
			}
		}
		else if (this.CurrentMethod.Type == CiSystem.VoidType)
			Write("false");
		else
			Write("NULL");
	}

	public override void Visit(CiThrow statement)
	{
		WriteDestructAll();
		Write("return ");
		WriteThrowReturnValue();
		WriteLine(';');
	}

	bool TryWriteCallAndReturn(CiStatement[] statements, int lastCallIndex, CiExpr returnValue)
	{
		if (this.VarsToDestruct.Count > 0)
			return false;
		CiExpr call = statements[lastCallIndex] as CiExpr;
		CiMethod throwingMethod = GetThrowingMethod(call);
		if (throwingMethod == null)
			return false;
		Write(statements, lastCallIndex);
		Write("return ");
		if (throwingMethod.Type is CiNumericType) {
			if (throwingMethod.Type is CiIntegerType) {
				call.Accept(this, CiPriority.Equality);
				Write(" != -1");
			}
			else {
				IncludeMath();
				Write("!isnan(");
				call.Accept(this, CiPriority.Argument);
				Write(')');
			}
		}
		else if (throwingMethod.Type == CiSystem.VoidType)
			call.Accept(this, CiPriority.Select);
		else {
			call.Accept(this, CiPriority.Equality);
			Write(" != NULL");
		}
		if (returnValue != null) {
			Write(" ? ");
			returnValue.Accept(this, CiPriority.Select);
			Write(" : ");
			WriteThrowReturnValue();
		}
		WriteLine(';');
		return true;
	}

	protected override void Write(CiStatement[] statements)
	{
		int i = statements.Length - 2;
		if (i >= 0 && statements[i + 1] is CiReturn ret && TryWriteCallAndReturn(statements, i, ret.Value))
			return;
		base.Write(statements);
	}

	void Write(CiEnum enu)
	{
		WriteLine();
		Write(enu.Documentation);
		Write("typedef enum ");
		OpenBlock();
		bool first = true;
		foreach (CiConst konst in enu) {
			if (!first)
				WriteLine(',');
			first = false;
			Write(konst.Documentation);
			WriteName(enu);
			Write('_');
			WriteUppercaseWithUnderscores(konst.Name);
			WriteExplicitEnumValue(konst);
		}
		WriteLine();
		this.Indent--;
		Write("} ");
		WriteName(enu);
		WriteLine(';');
	}

	void WriteTypedef(CiClass klass)
	{
		if (klass.CallType == CiCallType.Static)
			return;
		Write("typedef struct ");
		WriteName(klass);
		Write(' ');
		WriteName(klass);
		WriteLine(';');
	}

	protected void WriteTypedefs(CiProgram program, bool pub)
	{
		foreach (CiContainerType type in program) {
			if (type.IsPublic == pub) {
				switch (type) {
				case CiEnum enu:
					Write(enu);
					break;
				case CiClass klass:
					WriteTypedef(klass);
					break;
				default:
					throw new NotImplementedException(type.ToString());
				}
			}
		}
	}

	void WriteInstanceParameters(CiMethod method)
	{
		Write('(');
		if (!method.IsMutator)
			Write("const ");
		WriteName(method.Parent);
		Write(" *self");
		WriteParameters(method, false, false);
	}

	void WriteSignature(CiClass klass, CiMethod method)
	{
		if (!klass.IsPublic || method.Visibility != CiVisibility.Public)
			Write("static ");
		WriteSignature(method, () => {
			WriteName(klass);
			Write('_');
			Write(method.Name);
			if (method.CallType != CiCallType.Static)
				WriteInstanceParameters(method);
			else if (method.Parameters.Count == 0)
				Write("(void)");
			else
				WriteParameters(method, false);
		});
	}

	static CiClass GetVtblStructClass(CiClass klass)
	{
		while (!klass.AddsVirtualMethods)
			klass = (CiClass) klass.Parent;
		return klass;
	}

	static CiClass GetVtblPtrClass(CiClass klass)
	{
		for (CiClass result = null;;) {
			if (klass.AddsVirtualMethods)
				result = klass;
			if (!(klass.Parent is CiClass baseClass))
				return result;
			klass = baseClass;
		}
	}

	void WriteVtblFields(CiClass klass)
	{
		if (klass.Parent is CiClass baseClass)
			WriteVtblFields(baseClass);
		foreach (CiMethod method in klass.Methods) {
			if (method.IsAbstractOrVirtual) {
				WriteSignature(method, () => {
					Write("(*");
					WriteCamelCase(method.Name);
					Write(')');
					WriteInstanceParameters(method);
				});
				WriteLine(';');
			}
		}
	}

	void WriteVtblStruct(CiClass klass)
	{
		Write("typedef struct ");
		OpenBlock();
		WriteVtblFields(klass);
		this.Indent--;
		Write("} ");
		WriteName(klass);
		WriteLine("Vtbl;");
	}

	protected virtual string GetConst(CiArrayStorageType array) => "const ";

	protected override void WriteConst(CiConst konst)
	{
		if (konst.Type is CiArrayStorageType array) {
			Write("static ");
			Write(GetConst(array));
			WriteTypeAndName(konst);
			Write(" = ");
			konst.Value.Accept(this, CiPriority.Argument);
			WriteLine(';');
		}
		else if (konst.Visibility == CiVisibility.Public) {
			Write("#define ");
			WriteName(konst);
			Write(' ');
			konst.Value.Accept(this, CiPriority.Argument);
			WriteLine();
		}
	}

	static bool HasVtblValue(CiClass klass)
	{
		if (klass.CallType == CiCallType.Static || klass.CallType == CiCallType.Abstract)
			return false;
		return klass.Methods.Any(method => method.CallType == CiCallType.Virtual || method.CallType == CiCallType.Override || method.CallType == CiCallType.Sealed);
	}

	protected override bool NeedsConstructor(CiClass klass)
	{
		if (klass == CiSystem.MatchClass)
			return false;
		return base.NeedsConstructor(klass)
			|| HasVtblValue(klass)
			|| (klass.Parent is CiClass baseClass && NeedsConstructor(baseClass));
	}

	static bool NeedsDestructor(CiClass klass)
	{
		return klass.Fields.Any(field => NeedToDestruct(field))
			|| (klass.Parent is CiClass baseClass && NeedsDestructor(baseClass));
	}

	void WriteXstructorSignature(string name, CiClass klass)
	{
		Write("static void ");
		WriteName(klass);
		Write('_');
		Write(name);
		Write('(');
		WriteName(klass);
		Write(" *self)");
	}

	protected void WriteSignatures(CiClass klass, bool pub)
	{
		foreach (CiConst konst in klass.Consts) {
			if ((konst.Visibility == CiVisibility.Public) == pub) {
				if (pub) {
					WriteLine();
					Write(konst.Documentation);
				}
				WriteConst(konst);
			}
		}
		foreach (CiMethod method in klass.Methods) {
			if (method.IsLive && (method.Visibility == CiVisibility.Public) == pub && method.CallType != CiCallType.Abstract) {
				WriteLine();
				WriteDoc(method);
				WriteSignature(klass, method);
				WriteLine(';');
			}
		}
	}

	protected void WriteStruct(CiClass klass)
	{
		if (klass.CallType != CiCallType.Static) {
			// topological sorting of class hierarchy and class storage fields
			if (this.WrittenClasses.TryGetValue(klass, out bool done)) {
				if (done)
					return;
				throw new CiException(klass, "Circular dependency for class {0}", klass.Name);
			}
			this.WrittenClasses.Add(klass, false);
			if (klass.Parent is CiClass baseClass)
				WriteStruct(baseClass);
			foreach (CiField field in klass.Fields)
				if (field.Type.BaseType is CiClass fieldClass)
					WriteStruct(fieldClass);
			this.WrittenClasses[klass] = true;

			WriteLine();
			if (klass.AddsVirtualMethods)
				WriteVtblStruct(klass);
			Write(klass.Documentation);
			Write("struct ");
			WriteName(klass);
			Write(' ');
			OpenBlock();
			if (GetVtblPtrClass(klass) == klass) {
				Write("const ");
				WriteName(klass);
				WriteLine("Vtbl *vtbl;");
			}
			if (klass.Parent is CiClass) {
				WriteName(klass.Parent);
				WriteLine(" base;");
			}
			foreach (CiField field in klass.Fields) {
				WriteTypeAndName(field);
				WriteLine(';');
			}
			this.Indent--;
			WriteLine("};");
		}
		if (NeedsConstructor(klass)) {
			WriteXstructorSignature("Construct", klass);
			WriteLine(';');
		}
		if (NeedsDestructor(klass)) {
			WriteXstructorSignature("Destruct", klass);
			WriteLine(';');
		}
		WriteSignatures(klass, false);
	}

	void WriteVtbl(CiClass definingClass, CiClass declaringClass)
	{
		if (declaringClass.Parent is CiClass baseClass)
			WriteVtbl(definingClass, baseClass);
		foreach (CiMethod declaredMethod in declaringClass.Methods) {
			if (declaredMethod.IsAbstractOrVirtual) {
				CiSymbol definedMethod = definingClass.TryLookup(declaredMethod.Name);
				if (declaredMethod != definedMethod) {
					Write('(');
					WriteSignature(declaredMethod, () => {
						Write("(*)");
						WriteInstanceParameters(declaredMethod);
					});
					Write(") ");
				}
				WriteName(definedMethod);
				WriteLine(',');
			}
		}
	}

	protected void WriteConstructor(CiClass klass)
	{
		if (!NeedsConstructor(klass))
			return;
		this.StringSwitchesWithGoto.Clear();
		WriteLine();
		WriteXstructorSignature("Construct", klass);
		WriteLine();
		OpenBlock();
		if (klass.Parent is CiClass baseClass && NeedsConstructor(baseClass)) {
			WriteName(baseClass);
			WriteLine("_Construct(&self->base);");
		}
		if (HasVtblValue(klass)) {
			CiClass structClass = GetVtblStructClass(klass);
			Write("static const ");
			WriteName(structClass);
			Write("Vtbl vtbl = ");
			OpenBlock();
			WriteVtbl(klass, structClass);
			this.Indent--;
			WriteLine("};");
			CiClass ptrClass = GetVtblPtrClass(klass);
			WriteSelfForField(ptrClass);
			Write("vtbl = ");
			if (ptrClass != structClass) {
				Write("(const ");
				WriteName(ptrClass);
				Write("Vtbl *) ");
			}
			WriteLine("&vtbl;");
		}
		foreach (CiField field in klass.Fields)
			WriteInitCode(field);
		WriteConstructorBody(klass);
		CloseBlock();
	}

	protected void WriteDestructor(CiClass klass)
	{
		if (!NeedsDestructor(klass))
			return;
		WriteLine();
		WriteXstructorSignature("Destruct", klass);
		WriteLine();
		OpenBlock();
		foreach (CiField field in klass.Fields.Reverse())
			WriteDestruct(field);
		if (klass.Parent is CiClass baseClass && NeedsDestructor(baseClass)) {
			WriteName(baseClass);
			WriteLine("_Destruct(&self->base);");
		}
		CloseBlock();
	}

	void WriteNewDelete(CiClass klass, bool define)
	{
		if (!klass.IsPublic || klass.Constructor == null || klass.Constructor.Visibility != CiVisibility.Public)
			return;

		WriteLine();
		WriteName(klass);
		Write(" *");
		WriteName(klass);
		Write("_New(void)");
		if (define) {
			WriteLine();
			OpenBlock();
			WriteName(klass);
			Write(" *self = (");
			WriteName(klass);
			Write(" *) malloc(sizeof(");
			WriteName(klass);
			WriteLine("));");
			if (NeedsConstructor(klass)) {
				WriteLine("if (self != NULL)");
				this.Indent++;
				WriteName(klass);
				WriteLine("_Construct(self);");
				this.Indent--;
			}
			WriteLine("return self;");
			CloseBlock();
			WriteLine();
		}
		else
			WriteLine(';');

		Write("void ");
		WriteName(klass);
		Write("_Delete(");
		WriteName(klass);
		Write(" *self)");
		if (define) {
			WriteLine();
			OpenBlock();
			if (NeedsDestructor(klass)) {
				WriteLine("if (self == NULL)");
				this.Indent++;
				WriteLine("return;");
				this.Indent--;
				WriteName(klass);
				WriteLine("_Destruct(self);");
			}
			WriteLine("free(self);");
			CloseBlock();
		}
		else
			WriteLine(';');
	}

	protected void Write(CiClass klass, CiMethod method)
	{
		if (!method.IsLive || method.CallType == CiCallType.Abstract)
			return;
		this.StringSwitchesWithGoto.Clear();
		WriteLine();
		WriteSignature(klass, method);
		foreach (CiVar param in method.Parameters) {
			if (NeedToDestruct(param))
				this.VarsToDestruct.Add(param);
		}
		WriteLine();
		this.CurrentMethod = method;
		OpenBlock();
		if (method.Body is CiBlock block) {
			CiStatement[] statements = block.Statements;
			if (!block.CompletesNormally)
				Write(statements);
			else if (method.Throws && method.Type == CiSystem.VoidType) {
				if (statements.Length == 0 || !TryWriteCallAndReturn(statements, statements.Length - 1, null)) {
					Write(statements);
					WriteDestructAll();
					WriteLine("return true;");
				}
			}
			else {
				Write(statements);
				WriteDestructAll();
			}
		}
		else
			method.Body.Accept(this);
		this.CurrentTemporaries.Clear();
		this.VarsToDestruct.Clear();
		CloseBlock();
		this.CurrentMethod = null;
	}

	void WriteLibrary()
	{
		if (this.StringAssign) {
			WriteLine();
			WriteLine("static void CiString_Assign(char **str, char *value)");
			OpenBlock();
			WriteLine("free(*str);");
			WriteLine("*str = value;");
			CloseBlock();
		}
		if (this.StringSubstring) {
			WriteLine();
			WriteLine("static char *CiString_Substring(const char *str, int len)");
			OpenBlock();
			WriteLine("char *p = malloc(len + 1);");
			WriteLine("memcpy(p, str, len);");
			WriteLine("p[len] = '\\0';");
			WriteLine("return p;");
			CloseBlock();
		}
		if (this.StringAppend) {
			WriteLine();
			WriteLine("static void CiString_Append(char **str, const char *suffix)");
			OpenBlock();
			WriteLine("size_t suffixLen = strlen(suffix);");
			WriteLine("if (suffixLen == 0)");
			WriteLine("\treturn;");
			WriteLine("size_t prefixLen = strlen(*str);");
			WriteLine("*str = realloc(*str, prefixLen + suffixLen + 1);");
			WriteLine("memcpy(*str + prefixLen, suffix, suffixLen + 1);");
			CloseBlock();
		}
		if (this.StringIndexOf) {
			WriteLine();
			WriteLine("static int CiString_IndexOf(const char *str, const char *needle)");
			OpenBlock();
			WriteLine("const char *p = strstr(str, needle);");
			WriteLine("return p == NULL ? -1 : (int) (p - str);");
			CloseBlock();
		}
		if (this.StringLastIndexOf) {
			WriteLine();
			WriteLine("static int CiString_LastIndexOf(const char *str, const char *needle)");
			OpenBlock();
			WriteLine("if (needle[0] == '\\0')");
			WriteLine("\treturn (int) strlen(str);");
			WriteLine("int result = -1;");
			WriteLine("const char *p = strstr(str, needle);");
			Write("while (p != NULL) ");
			OpenBlock();
			WriteLine("result = (int) (p - str);");
			WriteLine("p = strstr(p + 1, needle);");
			CloseBlock();
			WriteLine("return result;");
			CloseBlock();
		}
		if (this.StringEndsWith) {
			WriteLine();
			WriteLine("static bool CiString_EndsWith(const char *str, const char *suffix)");
			OpenBlock();
			WriteLine("size_t strLen = strlen(str);");
			WriteLine("size_t suffixLen = strlen(suffix);");
			WriteLine("return strLen >= suffixLen && memcmp(str + strLen - suffixLen, suffix, suffixLen) == 0;");
			CloseBlock();
		}
		if (this.StringFormat) {
			WriteLine();
			WriteLine("static char *CiString_Format(const char *format, ...)");
			OpenBlock();
			WriteLine("va_list args1;");
			WriteLine("va_start(args1, format);");
			WriteLine("va_list args2;");
			WriteLine("va_copy(args2, args1);");
			WriteLine("size_t len = vsnprintf(NULL, 0, format, args1) + 1;");
			WriteLine("va_end(args1);");
			WriteLine("char *str = malloc(len);");
			WriteLine("vsnprintf(str, len, format, args2);");
			WriteLine("va_end(args2);");
			WriteLine("return str;");
			CloseBlock();
		}
		if (this.MatchFind) {
			WriteLine();
			WriteLine("static bool CiMatch_Find(GMatchInfo **match_info, const char *input, const char *pattern, GRegexCompileFlags options)");
			OpenBlock();
			WriteLine("GRegex *regex = g_regex_new(pattern, options, 0, NULL);");
			WriteLine("bool result = g_regex_match(regex, input, 0, match_info);");
			WriteLine("g_regex_unref(regex);");
			WriteLine("return result;");
			CloseBlock();
		}
		if (this.MatchPos) {
			WriteLine();
			WriteLine("static int CiMatch_GetPos(const GMatchInfo *match_info, int which)");
			OpenBlock();
			WriteLine("int start;");
			WriteLine("int end;");
			WriteLine("g_match_info_fetch_pos(match_info, 0, &start, &end);");
			WriteLine("switch (which) {");
			WriteLine("case 0:");
			WriteLine("\treturn start;");
			WriteLine("case 1:");
			WriteLine("\treturn end;");
			WriteLine("default:");
			WriteLine("\treturn end - start;");
			WriteLine('}');
			CloseBlock();
		}
		if (this.PtrConstruct) {
			WriteLine();
			WriteLine("static void CiPtr_Construct(void **ptr)");
			OpenBlock();
			WriteLine("*ptr = NULL;");
			CloseBlock();
		}
		if (this.SharedMake || this.SharedAddRef || this.SharedRelease) {
			WriteLine();
			WriteLine("typedef void (*CiMethodPtr)(void *);");
			WriteLine("typedef struct {");
			this.Indent++;
			WriteLine("size_t count;");
			WriteLine("size_t unitSize;");
			WriteLine("size_t refCount;");
			WriteLine("CiMethodPtr destructor;");
			this.Indent--;
			WriteLine("} CiShared;");
		}
		if (this.SharedMake) {
			WriteLine();
			WriteLine("static void *CiShared_Make(size_t count, size_t unitSize, CiMethodPtr constructor, CiMethodPtr destructor)");
			OpenBlock();
			WriteLine("CiShared *self = (CiShared *) malloc(sizeof(CiShared) + count * unitSize);");
			WriteLine("self->count = count;");
			WriteLine("self->unitSize = unitSize;");
			WriteLine("self->refCount = 1;");
			WriteLine("self->destructor = destructor;");
			Write("if (constructor != NULL) ");
			OpenBlock();
			WriteLine("for (size_t i = 0; i < count; i++)");
			WriteLine("\tconstructor((char *) (self + 1) + i * unitSize);");
			CloseBlock();
			WriteLine("return self + 1;");
			CloseBlock();
		}
		if (this.SharedAddRef) {
			WriteLine();
			WriteLine("static void *CiShared_AddRef(void *ptr)");
			OpenBlock();
			WriteLine("if (ptr != NULL)");
			WriteLine("\t((CiShared *) ptr)[-1].refCount++;");
			WriteLine("return ptr;");
			CloseBlock();
		}
		if (this.SharedRelease || this.SharedAssign || this.ListFrees.ContainsKey("Shared")) {
			WriteLine();
			WriteLine("static void CiShared_Release(void *ptr)");
			OpenBlock();
			WriteLine("if (ptr == NULL)");
			WriteLine("\treturn;");
			WriteLine("CiShared *self = (CiShared *) ptr - 1;");
			WriteLine("if (--self->refCount != 0)");
			WriteLine("\treturn;");
			Write("if (self->destructor != NULL) ");
			OpenBlock();
			WriteLine("for (size_t i = self->count; i > 0;)");
			WriteLine("\tself->destructor((char *) ptr + --i * self->unitSize);");
			CloseBlock();
			WriteLine("free(self);");
			CloseBlock();
		}
		if (this.SharedAssign) {
			WriteLine();
			WriteLine("static void CiShared_Assign(void **ptr, void *value)");
			OpenBlock();
			WriteLine("CiShared_Release(*ptr);");
			WriteLine("*ptr = value;");
			CloseBlock();
		}
		foreach (KeyValuePair<string, string> nameContent in this.ListFrees) {
			WriteLine();
			Write("static void CiList_Free");
			Write(nameContent.Key);
			WriteLine("(void *ptr)");
			OpenBlock();
			Write(nameContent.Value);
			WriteLine(';');
			CloseBlock();
		}
		if (this.TreeCompareInteger) {
			WriteLine();
			Write("static int CiTree_CompareInteger(gconstpointer pa, gconstpointer pb, gpointer user_data)");
			OpenBlock();
			WriteLine("gintptr a = (gintptr) pa;");
			WriteLine("gintptr b = (gintptr) pb;");
			WriteLine("return (a > b) - (a < b);");
			CloseBlock();
		}
		if (this.TreeCompareString) {
			WriteLine();
			Write("static int CiTree_CompareString(gconstpointer a, gconstpointer b, gpointer user_data)");
			OpenBlock();
			WriteLine("return strcmp((const char *) a, (const char *) b);");
			CloseBlock();
		}
		foreach (TypeCode typeCode in this.Compares) {
			WriteLine();
			Write("static int CiCompare_");
			Write(typeCode);
			WriteLine("(const void *pa, const void *pb)");
			OpenBlock();
			Write(typeCode);
			Write(" a = *(const ");
			Write(typeCode);
			WriteLine(" *) pa;");
			Write(typeCode);
			Write(" b = *(const ");
			Write(typeCode);
			WriteLine(" *) pb;");
			switch (typeCode) {
			case TypeCode.Byte:
			case TypeCode.SByte:
			case TypeCode.Int16:
			case TypeCode.UInt16:
				// subtraction can't overflow int
				WriteLine("return a - b;");
				break;
			default:
				WriteLine("return (a > b) - (a < b);");
				break;
			}
			CloseBlock();
		}
		foreach (TypeCode typeCode in this.Contains) {
			WriteLine();
			Write("static bool CiArray_Contains_");
			if (typeCode == TypeCode.String)
				Write("string(const char * const *a, size_t len, const char *");
			else {
				Write(typeCode);
				Write("(const ");
				Write(typeCode);
				Write(" *a, size_t len, ");
				Write(typeCode);
			}
			WriteLine(" value)");
			OpenBlock();
			WriteLine("for (size_t i = 0; i < len; i++)");
			if (typeCode == TypeCode.String)
				WriteLine("\tif (strcmp(a[i], value) == 0)");
			else
				WriteLine("\tif (a[i] == value)");
			WriteLine("\t\treturn true;");
			WriteLine("return false;");
			CloseBlock();
		}
	}

	protected void WriteResources(Dictionary<string, byte[]> resources)
	{
		if (resources.Count == 0)
			return;
		WriteLine();
		foreach (string name in resources.Keys.OrderBy(k => k)) {
			Write("static const ");
			Write(TypeCode.Byte);
			Write(' ');
			WriteResource(name, -1);
			Write('[');
			VisitLiteralLong(resources[name].Length);
			WriteLine("] = {");
			Write('\t');
			Write(resources[name]);
			WriteLine(" };");
		}
	}

	public override void Write(CiProgram program)
	{
		this.WrittenClasses.Clear();
		string headerFile = Path.ChangeExtension(this.OutputFile, "h");
		SortedSet<string> headerIncludes = new SortedSet<string>();
		this.Includes = headerIncludes;
		OpenStringWriter();
		foreach (CiClass klass in program.Classes) {
			WriteNewDelete(klass, false);
			WriteSignatures(klass, true);
		}

		CreateFile(headerFile);
		WriteLine("#pragma once");
		WriteIncludes();
		WriteLine("#ifdef __cplusplus");
		WriteLine("extern \"C\" {");
		WriteLine("#endif");
		WriteTypedefs(program, true);
		CloseStringWriter();
		WriteLine();
		WriteLine("#ifdef __cplusplus");
		WriteLine('}');
		WriteLine("#endif");
		CloseFile();

		this.Includes = new SortedSet<string>();
		this.StringAssign = false;
		this.StringSubstring = false;
		this.StringAppend = false;
		this.StringIndexOf = false;
		this.StringLastIndexOf = false;
		this.StringEndsWith = false;
		this.StringFormat = false;
		this.MatchFind = false;
		this.MatchPos = false;
		this.PtrConstruct = false;
		this.SharedMake = false;
		this.SharedAddRef = false;
		this.SharedRelease = false;
		this.SharedAssign = false;
		this.ListFrees.Clear();
		this.TreeCompareInteger = false;
		this.TreeCompareString = false;
		this.Compares.Clear();
		this.Contains.Clear();
		OpenStringWriter();
		foreach (CiClass klass in program.Classes)
			WriteStruct(klass);
		WriteResources(program.Resources);
		foreach (CiClass klass in program.Classes) {
			this.CurrentClass = klass;
			WriteConstructor(klass);
			WriteDestructor(klass);
			WriteNewDelete(klass, true);
			foreach (CiMethod method in klass.Methods)
				Write(klass, method);
		}

		CreateFile(this.OutputFile);
		WriteTopLevelNatives(program);
		this.Includes.ExceptWith(headerIncludes);
		this.Includes.Add("stdlib.h");
		WriteIncludes();
		Write("#include \"");
		Write(Path.GetFileName(headerFile));
		WriteLine("\"");
		WriteLibrary();
		WriteTypedefs(program, false);
		CloseStringWriter();
		CloseFile();
	}
}

}