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
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
|
/*************************************************************************/
/* bindings_generator.cpp */
/*************************************************************************/
/* This file is part of: */
/* GODOT ENGINE */
/* https://godotengine.org */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur. */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md). */
/* */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the */
/* "Software"), to deal in the Software without restriction, including */
/* without limitation the rights to use, copy, modify, merge, publish, */
/* distribute, sublicense, and/or sell copies of the Software, and to */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions: */
/* */
/* The above copyright notice and this permission notice shall be */
/* included in all copies or substantial portions of the Software. */
/* */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
/*************************************************************************/
#include "bindings_generator.h"
#if defined(DEBUG_METHODS_ENABLED) && defined(TOOLS_ENABLED)
#include "core/config/engine.h"
#include "core/core_constants.h"
#include "core/io/compression.h"
#include "core/io/dir_access.h"
#include "core/io/file_access.h"
#include "core/os/os.h"
#include "core/string/ucaps.h"
#include "main/main.h"
#include "../godotsharp_defs.h"
#include "../utils/path_utils.h"
#include "../utils/string_utils.h"
StringBuilder &operator<<(StringBuilder &r_sb, const String &p_string) {
r_sb.append(p_string);
return r_sb;
}
StringBuilder &operator<<(StringBuilder &r_sb, const char *p_cstring) {
r_sb.append(p_cstring);
return r_sb;
}
#define CS_INDENT " " // 4 whitespaces
#define INDENT1 CS_INDENT
#define INDENT2 INDENT1 INDENT1
#define INDENT3 INDENT2 INDENT1
#define INDENT4 INDENT3 INDENT1
#define MEMBER_BEGIN "\n" INDENT1
#define OPEN_BLOCK "{\n"
#define CLOSE_BLOCK "}\n"
#define OPEN_BLOCK_L1 INDENT1 OPEN_BLOCK
#define OPEN_BLOCK_L2 INDENT2 OPEN_BLOCK
#define CLOSE_BLOCK_L1 INDENT1 CLOSE_BLOCK
#define CLOSE_BLOCK_L2 INDENT2 CLOSE_BLOCK
#define CLOSE_BLOCK_L3 INDENT3 CLOSE_BLOCK
#define BINDINGS_GLOBAL_SCOPE_CLASS "GD"
#define BINDINGS_NATIVE_NAME_FIELD "NativeName"
#define CS_PARAM_MEMORYOWN "memoryOwn"
#define CS_PARAM_METHODBIND "method"
#define CS_PARAM_INSTANCE "ptr"
#define CS_STATIC_METHOD_GETINSTANCE "GetPtr"
#define CS_METHOD_CALL "Call"
#define CS_PROPERTY_SINGLETON "Singleton"
#define CS_METHOD_INVOKE_GODOT_CLASS_METHOD "InvokeGodotClassMethod"
#define CS_METHOD_HAS_GODOT_CLASS_METHOD "HasGodotClassMethod"
#define CS_STATIC_FIELD_NATIVE_CTOR "NativeCtor"
#define CS_STATIC_FIELD_METHOD_BIND_PREFIX "MethodBind"
#define CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX "MethodProxyName_"
#define ICALL_PREFIX "godot_icall_"
#define ICALL_CLASSDB_GET_METHOD "ClassDB_get_method"
#define ICALL_CLASSDB_GET_CONSTRUCTOR "ClassDB_get_constructor"
#define C_LOCAL_RET "ret"
#define C_LOCAL_VARARG_RET "vararg_ret"
#define C_LOCAL_PTRCALL_ARGS "call_args"
#define C_CLASS_NATIVE_FUNCS "NativeFuncs"
#define C_NS_MONOUTILS "InteropUtils"
#define C_METHOD_UNMANAGED_GET_MANAGED C_NS_MONOUTILS ".UnmanagedGetManaged"
#define C_METHOD_ENGINE_GET_SINGLETON C_NS_MONOUTILS ".EngineGetSingleton"
#define C_NS_MONOMARSHAL "Marshaling"
#define C_METHOD_MONOSTR_TO_GODOT C_NS_MONOMARSHAL ".ConvertStringToNative"
#define C_METHOD_MONOSTR_FROM_GODOT C_NS_MONOMARSHAL ".ConvertStringToManaged"
#define C_METHOD_MONOARRAY_TO(m_type) C_NS_MONOMARSHAL ".ConvertSystemArrayToNative" #m_type
#define C_METHOD_MONOARRAY_FROM(m_type) C_NS_MONOMARSHAL ".ConvertNative" #m_type "ToSystemArray"
#define C_METHOD_MANAGED_TO_CALLABLE C_NS_MONOMARSHAL ".ConvertCallableToNative"
#define C_METHOD_MANAGED_FROM_CALLABLE C_NS_MONOMARSHAL ".ConvertCallableToManaged"
#define C_METHOD_MANAGED_TO_SIGNAL C_NS_MONOMARSHAL ".ConvertSignalToNative"
#define C_METHOD_MANAGED_FROM_SIGNAL C_NS_MONOMARSHAL ".ConvertSignalToManaged"
// Types that will be ignored by the generator and won't be available in C#.
const Vector<String> ignored_types = { "PhysicsServer3DExtension" };
void BindingsGenerator::TypeInterface::postsetup_enum_type(BindingsGenerator::TypeInterface &r_enum_itype) {
// C interface for enums is the same as that of 'uint32_t'. Remember to apply
// any of the changes done here to the 'uint32_t' type interface as well.
r_enum_itype.cs_type = r_enum_itype.proxy_name;
r_enum_itype.cs_in_expr = "(int)%0";
r_enum_itype.cs_out = "%5return (%2)%0(%1);";
{
// The expected types for parameters and return value in ptrcall are 'int64_t' or 'uint64_t'.
r_enum_itype.c_in = "%5%0 %1_in = %1;\n";
r_enum_itype.c_out = "%5return (%0)%1;\n";
r_enum_itype.c_type = "long";
r_enum_itype.c_arg_in = "&%s_in";
}
r_enum_itype.c_type_in = "int";
r_enum_itype.c_type_out = r_enum_itype.c_type_in;
r_enum_itype.class_doc = &EditorHelp::get_doc_data()->class_list[r_enum_itype.proxy_name];
}
static String fix_doc_description(const String &p_bbcode) {
// This seems to be the correct way to do this. It's the same EditorHelp does.
return p_bbcode.dedent()
.replace("\t", "")
.replace("\r", "")
.strip_edges();
}
static String snake_to_pascal_case(const String &p_identifier, bool p_input_is_upper = false) {
String ret;
Vector<String> parts = p_identifier.split("_", true);
for (int i = 0; i < parts.size(); i++) {
String part = parts[i];
if (part.length()) {
part[0] = _find_upper(part[0]);
if (p_input_is_upper) {
for (int j = 1; j < part.length(); j++) {
part[j] = _find_lower(part[j]);
}
}
ret += part;
} else {
if (i == 0 || i == (parts.size() - 1)) {
// Preserve underscores at the beginning and end
ret += "_";
} else {
// Preserve contiguous underscores
if (parts[i - 1].length()) {
ret += "__";
} else {
ret += "_";
}
}
}
}
return ret;
}
static String snake_to_camel_case(const String &p_identifier, bool p_input_is_upper = false) {
String ret;
Vector<String> parts = p_identifier.split("_", true);
for (int i = 0; i < parts.size(); i++) {
String part = parts[i];
if (part.length()) {
if (i != 0) {
part[0] = _find_upper(part[0]);
}
if (p_input_is_upper) {
for (int j = i != 0 ? 1 : 0; j < part.length(); j++) {
part[j] = _find_lower(part[j]);
}
}
ret += part;
} else {
if (i == 0 || i == (parts.size() - 1)) {
// Preserve underscores at the beginning and end
ret += "_";
} else {
// Preserve contiguous underscores
if (parts[i - 1].length()) {
ret += "__";
} else {
ret += "_";
}
}
}
}
return ret;
}
String BindingsGenerator::bbcode_to_xml(const String &p_bbcode, const TypeInterface *p_itype) {
// Based on the version in EditorHelp
if (p_bbcode.is_empty()) {
return String();
}
DocTools *doc = EditorHelp::get_doc_data();
String bbcode = p_bbcode;
StringBuilder xml_output;
xml_output.append("<para>");
List<String> tag_stack;
bool code_tag = false;
int pos = 0;
while (pos < bbcode.length()) {
int brk_pos = bbcode.find("[", pos);
if (brk_pos < 0) {
brk_pos = bbcode.length();
}
if (brk_pos > pos) {
String text = bbcode.substr(pos, brk_pos - pos);
if (code_tag || tag_stack.size() > 0) {
xml_output.append(text.xml_escape());
} else {
Vector<String> lines = text.split("\n");
for (int i = 0; i < lines.size(); i++) {
if (i != 0) {
xml_output.append("<para>");
}
xml_output.append(lines[i].xml_escape());
if (i != lines.size() - 1) {
xml_output.append("</para>\n");
}
}
}
}
if (brk_pos == bbcode.length()) {
break; // nothing else to add
}
int brk_end = bbcode.find("]", brk_pos + 1);
if (brk_end == -1) {
String text = bbcode.substr(brk_pos, bbcode.length() - brk_pos);
if (code_tag || tag_stack.size() > 0) {
xml_output.append(text.xml_escape());
} else {
Vector<String> lines = text.split("\n");
for (int i = 0; i < lines.size(); i++) {
if (i != 0) {
xml_output.append("<para>");
}
xml_output.append(lines[i].xml_escape());
if (i != lines.size() - 1) {
xml_output.append("</para>\n");
}
}
}
break;
}
String tag = bbcode.substr(brk_pos + 1, brk_end - brk_pos - 1);
if (tag.begins_with("/")) {
bool tag_ok = tag_stack.size() && tag_stack.front()->get() == tag.substr(1, tag.length());
if (!tag_ok) {
xml_output.append("[");
pos = brk_pos + 1;
continue;
}
tag_stack.pop_front();
pos = brk_end + 1;
code_tag = false;
if (tag == "/url") {
xml_output.append("</a>");
} else if (tag == "/code") {
xml_output.append("</c>");
} else if (tag == "/codeblock") {
xml_output.append("</code>");
}
} else if (code_tag) {
xml_output.append("[");
pos = brk_pos + 1;
} else if (tag.begins_with("method ") || tag.begins_with("member ") || tag.begins_with("signal ") || tag.begins_with("enum ") || tag.begins_with("constant ") || tag.begins_with("theme_item ")) {
const int tag_end = tag.find(" ");
const String link_tag = tag.substr(0, tag_end);
const String link_target = tag.substr(tag_end + 1, tag.length()).lstrip(" ");
const Vector<String> link_target_parts = link_target.split(".");
if (link_target_parts.size() <= 0 || link_target_parts.size() > 2) {
ERR_PRINT("Invalid reference format: '" + tag + "'.");
xml_output.append("<c>");
xml_output.append(tag);
xml_output.append("</c>");
pos = brk_end + 1;
continue;
}
const TypeInterface *target_itype;
StringName target_cname;
if (link_target_parts.size() == 2) {
target_itype = _get_type_or_null(TypeReference(link_target_parts[0]));
if (!target_itype) {
target_itype = _get_type_or_null(TypeReference("_" + link_target_parts[0]));
}
target_cname = link_target_parts[1];
} else {
target_itype = p_itype;
target_cname = link_target_parts[0];
}
if (link_tag == "method") {
_append_xml_method(xml_output, target_itype, target_cname, link_target, link_target_parts);
} else if (link_tag == "member") {
_append_xml_member(xml_output, target_itype, target_cname, link_target, link_target_parts);
} else if (link_tag == "signal") {
_append_xml_signal(xml_output, target_itype, target_cname, link_target, link_target_parts);
} else if (link_tag == "enum") {
_append_xml_enum(xml_output, target_itype, target_cname, link_target, link_target_parts);
} else if (link_tag == "constant") {
_append_xml_constant(xml_output, target_itype, target_cname, link_target, link_target_parts);
} else if (link_tag == "theme_item") {
// We do not declare theme_items in any way in C#, so there is nothing to reference
_append_xml_undeclared(xml_output, link_target);
}
pos = brk_end + 1;
} else if (doc->class_list.has(tag)) {
if (tag == "Array" || tag == "Dictionary") {
xml_output.append("<see cref=\"" BINDINGS_NAMESPACE_COLLECTIONS ".");
xml_output.append(tag);
xml_output.append("\"/>");
} else if (tag == "bool" || tag == "int") {
xml_output.append("<see cref=\"");
xml_output.append(tag);
xml_output.append("\"/>");
} else if (tag == "float") {
xml_output.append("<see cref=\""
#ifdef REAL_T_IS_DOUBLE
"double"
#else
"float"
#endif
"\"/>");
} else if (tag == "Variant") {
// We use System.Object for Variant, so there is no Variant type in C#
xml_output.append("<c>Variant</c>");
} else if (tag == "String") {
xml_output.append("<see cref=\"string\"/>");
} else if (tag == "Nil") {
xml_output.append("<see langword=\"null\"/>");
} else if (tag.begins_with("@")) {
// @GlobalScope, @GDScript, etc
xml_output.append("<c>");
xml_output.append(tag);
xml_output.append("</c>");
} else if (tag == "PackedByteArray") {
xml_output.append("<see cref=\"byte\"/>[]");
} else if (tag == "PackedInt32Array") {
xml_output.append("<see cref=\"int\"/>[]");
} else if (tag == "PackedInt64Array") {
xml_output.append("<see cref=\"long\"/>[]");
} else if (tag == "PackedFloat32Array") {
xml_output.append("<see cref=\"float\"/>[]");
} else if (tag == "PackedFloat64Array") {
xml_output.append("<see cref=\"double\"/>[]");
} else if (tag == "PackedStringArray") {
xml_output.append("<see cref=\"string\"/>[]");
} else if (tag == "PackedVector2Array") {
xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector2\"/>[]");
} else if (tag == "PackedVector3Array") {
xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Vector3\"/>[]");
} else if (tag == "PackedColorArray") {
xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".Color\"/>[]");
} else {
const TypeInterface *target_itype = _get_type_or_null(TypeReference(tag));
if (!target_itype) {
target_itype = _get_type_or_null(TypeReference("_" + tag));
}
if (target_itype) {
xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
xml_output.append(target_itype->proxy_name);
xml_output.append("\"/>");
} else {
ERR_PRINT("Cannot resolve type reference in documentation: '" + tag + "'.");
xml_output.append("<c>");
xml_output.append(tag);
xml_output.append("</c>");
}
}
pos = brk_end + 1;
} else if (tag == "b") {
// bold is not supported in xml comments
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "i") {
// italics is not supported in xml comments
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "code") {
xml_output.append("<c>");
code_tag = true;
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "codeblock") {
xml_output.append("<code>");
code_tag = true;
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "kbd") {
// keyboard combinations are not supported in xml comments
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "center") {
// center alignment is not supported in xml comments
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "br") {
xml_output.append("\n"); // FIXME: Should use <para> instead. Luckily this tag isn't used for now.
pos = brk_end + 1;
} else if (tag == "u") {
// underline is not supported in xml comments
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "s") {
// strikethrough is not supported in xml comments
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag == "url") {
int end = bbcode.find("[", brk_end);
if (end == -1) {
end = bbcode.length();
}
String url = bbcode.substr(brk_end + 1, end - brk_end - 1);
xml_output.append("<a href=\"");
xml_output.append(url);
xml_output.append("\">");
xml_output.append(url);
pos = brk_end + 1;
tag_stack.push_front(tag);
} else if (tag.begins_with("url=")) {
String url = tag.substr(4, tag.length());
xml_output.append("<a href=\"");
xml_output.append(url);
xml_output.append("\">");
pos = brk_end + 1;
tag_stack.push_front("url");
} else if (tag == "img") {
int end = bbcode.find("[", brk_end);
if (end == -1) {
end = bbcode.length();
}
String image = bbcode.substr(brk_end + 1, end - brk_end - 1);
// Not supported. Just append the bbcode.
xml_output.append("[img]");
xml_output.append(image);
xml_output.append("[/img]");
pos = end;
tag_stack.push_front(tag);
} else if (tag.begins_with("color=")) {
// Not supported.
pos = brk_end + 1;
tag_stack.push_front("color");
} else if (tag.begins_with("font=")) {
// Not supported.
pos = brk_end + 1;
tag_stack.push_front("font");
} else {
xml_output.append("["); // ignore
pos = brk_pos + 1;
}
}
xml_output.append("</para>");
return xml_output.as_string();
}
void BindingsGenerator::_append_xml_method(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) {
if (OS::get_singleton()->is_stdout_verbose()) {
OS::get_singleton()->print("Cannot resolve @GlobalScope method reference in documentation: %s\n", p_link_target.utf8().get_data());
}
// TODO Map what we can
_append_xml_undeclared(p_xml_output, p_link_target);
} else if (!p_target_itype || !p_target_itype->is_object_type) {
if (OS::get_singleton()->is_stdout_verbose()) {
if (p_target_itype) {
OS::get_singleton()->print("Cannot resolve method reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data());
} else {
OS::get_singleton()->print("Cannot resolve type from method reference in documentation: %s\n", p_link_target.utf8().get_data());
}
}
// TODO Map what we can
_append_xml_undeclared(p_xml_output, p_link_target);
} else {
if (p_target_cname == "_init") {
// The _init method is not declared in C#, reference the constructor instead
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(p_target_itype->proxy_name);
p_xml_output.append(".");
p_xml_output.append(p_target_itype->proxy_name);
p_xml_output.append("()\"/>");
} else {
const MethodInterface *target_imethod = p_target_itype->find_method_by_name(p_target_cname);
if (target_imethod) {
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(p_target_itype->proxy_name);
p_xml_output.append(".");
p_xml_output.append(target_imethod->proxy_name);
p_xml_output.append("\"/>");
} else {
ERR_PRINT("Cannot resolve method reference in documentation: '" + p_link_target + "'.");
_append_xml_undeclared(p_xml_output, p_link_target);
}
}
}
}
void BindingsGenerator::_append_xml_member(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
if (p_link_target.find("/") >= 0) {
// Properties with '/' (slash) in the name are not declared in C#, so there is nothing to reference.
_append_xml_undeclared(p_xml_output, p_link_target);
} else if (!p_target_itype || !p_target_itype->is_object_type) {
if (OS::get_singleton()->is_stdout_verbose()) {
if (p_target_itype) {
OS::get_singleton()->print("Cannot resolve member reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data());
} else {
OS::get_singleton()->print("Cannot resolve type from member reference in documentation: %s\n", p_link_target.utf8().get_data());
}
}
// TODO Map what we can
_append_xml_undeclared(p_xml_output, p_link_target);
} else {
const TypeInterface *current_itype = p_target_itype;
const PropertyInterface *target_iprop = nullptr;
while (target_iprop == nullptr && current_itype != nullptr) {
target_iprop = current_itype->find_property_by_name(p_target_cname);
if (target_iprop == nullptr) {
current_itype = _get_type_or_null(TypeReference(current_itype->base_name));
}
}
if (target_iprop) {
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(current_itype->proxy_name);
p_xml_output.append(".");
p_xml_output.append(target_iprop->proxy_name);
p_xml_output.append("\"/>");
} else {
ERR_PRINT("Cannot resolve member reference in documentation: '" + p_link_target + "'.");
_append_xml_undeclared(p_xml_output, p_link_target);
}
}
}
void BindingsGenerator::_append_xml_signal(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
if (!p_target_itype || !p_target_itype->is_object_type) {
if (OS::get_singleton()->is_stdout_verbose()) {
if (p_target_itype) {
OS::get_singleton()->print("Cannot resolve signal reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data());
} else {
OS::get_singleton()->print("Cannot resolve type from signal reference in documentation: %s\n", p_link_target.utf8().get_data());
}
}
// TODO Map what we can
_append_xml_undeclared(p_xml_output, p_link_target);
} else {
const SignalInterface *target_isignal = p_target_itype->find_signal_by_name(p_target_cname);
if (target_isignal) {
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(p_target_itype->proxy_name);
p_xml_output.append(".");
p_xml_output.append(target_isignal->proxy_name);
p_xml_output.append("\"/>");
} else {
ERR_PRINT("Cannot resolve signal reference in documentation: '" + p_link_target + "'.");
_append_xml_undeclared(p_xml_output, p_link_target);
}
}
}
void BindingsGenerator::_append_xml_enum(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
const StringName search_cname = !p_target_itype ? p_target_cname : StringName(p_target_itype->name + "." + (String)p_target_cname);
HashMap<StringName, TypeInterface>::ConstIterator enum_match = enum_types.find(search_cname);
if (!enum_match && search_cname != p_target_cname) {
enum_match = enum_types.find(p_target_cname);
}
if (enum_match) {
const TypeInterface &target_enum_itype = enum_match->value;
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(target_enum_itype.proxy_name); // Includes nesting class if any
p_xml_output.append("\"/>");
} else {
ERR_PRINT("Cannot resolve enum reference in documentation: '" + p_link_target + "'.");
_append_xml_undeclared(p_xml_output, p_link_target);
}
}
void BindingsGenerator::_append_xml_constant(StringBuilder &p_xml_output, const TypeInterface *p_target_itype, const StringName &p_target_cname, const String &p_link_target, const Vector<String> &p_link_target_parts) {
if (p_link_target_parts[0] == name_cache.type_at_GlobalScope) {
_append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target);
} else if (!p_target_itype || !p_target_itype->is_object_type) {
// Search in @GlobalScope as a last resort if no class was specified
if (p_link_target_parts.size() == 1) {
_append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target);
return;
}
if (OS::get_singleton()->is_stdout_verbose()) {
if (p_target_itype) {
OS::get_singleton()->print("Cannot resolve constant reference for non-Godot.Object type in documentation: %s\n", p_link_target.utf8().get_data());
} else {
OS::get_singleton()->print("Cannot resolve type from constant reference in documentation: %s\n", p_link_target.utf8().get_data());
}
}
// TODO Map what we can
_append_xml_undeclared(p_xml_output, p_link_target);
} else {
// Try to find the constant in the current class
const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, p_target_itype->constants);
if (target_iconst) {
// Found constant in current class
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(p_target_itype->proxy_name);
p_xml_output.append(".");
p_xml_output.append(target_iconst->proxy_name);
p_xml_output.append("\"/>");
} else {
// Try to find as enum constant in the current class
const EnumInterface *target_ienum = nullptr;
for (const EnumInterface &ienum : p_target_itype->enums) {
target_ienum = &ienum;
target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants);
if (target_iconst) {
break;
}
}
if (target_iconst) {
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(p_target_itype->proxy_name);
p_xml_output.append(".");
p_xml_output.append(target_ienum->cname);
p_xml_output.append(".");
p_xml_output.append(target_iconst->proxy_name);
p_xml_output.append("\"/>");
} else if (p_link_target_parts.size() == 1) {
// Also search in @GlobalScope as a last resort if no class was specified
_append_xml_constant_in_global_scope(p_xml_output, p_target_cname, p_link_target);
} else {
ERR_PRINT("Cannot resolve constant reference in documentation: '" + p_link_target + "'.");
_append_xml_undeclared(p_xml_output, p_link_target);
}
}
}
}
void BindingsGenerator::_append_xml_constant_in_global_scope(StringBuilder &p_xml_output, const String &p_target_cname, const String &p_link_target) {
// Try to find as a global constant
const ConstantInterface *target_iconst = find_constant_by_name(p_target_cname, global_constants);
if (target_iconst) {
// Found global constant
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE "." BINDINGS_GLOBAL_SCOPE_CLASS ".");
p_xml_output.append(target_iconst->proxy_name);
p_xml_output.append("\"/>");
} else {
// Try to find as global enum constant
const EnumInterface *target_ienum = nullptr;
for (const EnumInterface &ienum : global_enums) {
target_ienum = &ienum;
target_iconst = find_constant_by_name(p_target_cname, target_ienum->constants);
if (target_iconst) {
break;
}
}
if (target_iconst) {
p_xml_output.append("<see cref=\"" BINDINGS_NAMESPACE ".");
p_xml_output.append(target_ienum->cname);
p_xml_output.append(".");
p_xml_output.append(target_iconst->proxy_name);
p_xml_output.append("\"/>");
} else {
ERR_PRINT("Cannot resolve global constant reference in documentation: '" + p_link_target + "'.");
_append_xml_undeclared(p_xml_output, p_link_target);
}
}
}
void BindingsGenerator::_append_xml_undeclared(StringBuilder &p_xml_output, const String &p_link_target) {
p_xml_output.append("<c>");
p_xml_output.append(p_link_target);
p_xml_output.append("</c>");
}
int BindingsGenerator::_determine_enum_prefix(const EnumInterface &p_ienum) {
CRASH_COND(p_ienum.constants.is_empty());
const ConstantInterface &front_iconstant = p_ienum.constants.front()->get();
Vector<String> front_parts = front_iconstant.name.split("_", /* p_allow_empty: */ true);
int candidate_len = front_parts.size() - 1;
if (candidate_len == 0) {
return 0;
}
for (const ConstantInterface &iconstant : p_ienum.constants) {
Vector<String> parts = iconstant.name.split("_", /* p_allow_empty: */ true);
int i;
for (i = 0; i < candidate_len && i < parts.size(); i++) {
if (front_parts[i] != parts[i]) {
// HARDCODED: Some Flag enums have the prefix 'FLAG_' for everything except 'FLAGS_DEFAULT' (same for 'METHOD_FLAG_' and'METHOD_FLAGS_DEFAULT').
bool hardcoded_exc = (i == candidate_len - 1 && ((front_parts[i] == "FLAGS" && parts[i] == "FLAG") || (front_parts[i] == "FLAG" && parts[i] == "FLAGS")));
if (!hardcoded_exc) {
break;
}
}
}
candidate_len = i;
if (candidate_len == 0) {
return 0;
}
}
return candidate_len;
}
void BindingsGenerator::_apply_prefix_to_enum_constants(BindingsGenerator::EnumInterface &p_ienum, int p_prefix_length) {
if (p_prefix_length > 0) {
for (ConstantInterface &iconstant : p_ienum.constants) {
int curr_prefix_length = p_prefix_length;
String constant_name = iconstant.name;
Vector<String> parts = constant_name.split("_", /* p_allow_empty: */ true);
if (parts.size() <= curr_prefix_length) {
continue;
}
if (is_digit(parts[curr_prefix_length][0])) {
// The name of enum constants may begin with a numeric digit when strip from the enum prefix,
// so we make the prefix for this constant one word shorter in those cases.
for (curr_prefix_length = curr_prefix_length - 1; curr_prefix_length > 0; curr_prefix_length--) {
if (!is_digit(parts[curr_prefix_length][0])) {
break;
}
}
}
constant_name = "";
for (int i = curr_prefix_length; i < parts.size(); i++) {
if (i > curr_prefix_length) {
constant_name += "_";
}
constant_name += parts[i];
}
iconstant.proxy_name = snake_to_pascal_case(constant_name, true);
}
}
}
Error BindingsGenerator::_populate_method_icalls_table(const TypeInterface &p_itype) {
for (const MethodInterface &imethod : p_itype.methods) {
if (imethod.is_virtual) {
continue;
}
const TypeInterface *return_type = _get_type_or_null(imethod.return_type);
ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
String im_unique_sig = get_ret_unique_sig(return_type) + ",CallMethodBind";
if (!imethod.is_static) {
im_unique_sig += ",CallInstance";
}
// Get arguments information
for (const ArgumentInterface &iarg : imethod.arguments) {
const TypeInterface *arg_type = _get_type_or_null(iarg.type);
ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
im_unique_sig += ",";
im_unique_sig += get_arg_unique_sig(*arg_type);
}
// godot_icall_{argc}_{icallcount}
String icall_method = ICALL_PREFIX;
icall_method += itos(imethod.arguments.size());
icall_method += "_";
icall_method += itos(method_icalls.size());
InternalCall im_icall = InternalCall(p_itype.api_type, icall_method, im_unique_sig);
im_icall.is_vararg = imethod.is_vararg;
im_icall.is_static = imethod.is_static;
im_icall.return_type = imethod.return_type;
for (const List<ArgumentInterface>::Element *F = imethod.arguments.front(); F; F = F->next()) {
im_icall.argument_types.push_back(F->get().type);
}
List<InternalCall>::Element *match = method_icalls.find(im_icall);
if (match) {
if (p_itype.api_type != ClassDB::API_EDITOR) {
match->get().editor_only = false;
}
method_icalls_map.insert(&imethod, &match->get());
} else {
List<InternalCall>::Element *added = method_icalls.push_back(im_icall);
method_icalls_map.insert(&imethod, &added->get());
}
}
return OK;
}
void BindingsGenerator::_generate_array_extensions(StringBuilder &p_output) {
p_output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
p_output.append("using System;\n\n");
// The class where we put the extensions doesn't matter, so just use "GD".
p_output.append("public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n{");
#define ARRAY_IS_EMPTY(m_type) \
p_output.append("\n" INDENT1 "/// <summary>\n"); \
p_output.append(INDENT1 "/// Returns true if this " #m_type " array is empty or doesn't exist.\n"); \
p_output.append(INDENT1 "/// </summary>\n"); \
p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array check.</param>\n"); \
p_output.append(INDENT1 "/// <returns>Whether or not the array is empty.</returns>\n"); \
p_output.append(INDENT1 "public static bool IsEmpty(this " #m_type "[] instance)\n"); \
p_output.append(OPEN_BLOCK_L1); \
p_output.append(INDENT2 "return instance == null || instance.Length == 0;\n"); \
p_output.append(INDENT1 CLOSE_BLOCK);
#define ARRAY_JOIN(m_type) \
p_output.append("\n" INDENT1 "/// <summary>\n"); \
p_output.append(INDENT1 "/// Converts this " #m_type " array to a string delimited by the given string.\n"); \
p_output.append(INDENT1 "/// </summary>\n"); \
p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
p_output.append(INDENT1 "/// <param name=\"delimiter\">The delimiter to use between items.</param>\n"); \
p_output.append(INDENT1 "/// <returns>A single string with all items.</returns>\n"); \
p_output.append(INDENT1 "public static string Join(this " #m_type "[] instance, string delimiter = \", \")\n"); \
p_output.append(OPEN_BLOCK_L1); \
p_output.append(INDENT2 "return String.Join(delimiter, instance);\n"); \
p_output.append(INDENT1 CLOSE_BLOCK);
#define ARRAY_STRINGIFY(m_type) \
p_output.append("\n" INDENT1 "/// <summary>\n"); \
p_output.append(INDENT1 "/// Converts this " #m_type " array to a string with brackets.\n"); \
p_output.append(INDENT1 "/// </summary>\n"); \
p_output.append(INDENT1 "/// <param name=\"instance\">The " #m_type " array to convert.</param>\n"); \
p_output.append(INDENT1 "/// <returns>A single string with all items.</returns>\n"); \
p_output.append(INDENT1 "public static string Stringify(this " #m_type "[] instance)\n"); \
p_output.append(OPEN_BLOCK_L1); \
p_output.append(INDENT2 "return \"[\" + instance.Join() + \"]\";\n"); \
p_output.append(INDENT1 CLOSE_BLOCK);
#define ARRAY_ALL(m_type) \
ARRAY_IS_EMPTY(m_type) \
ARRAY_JOIN(m_type) \
ARRAY_STRINGIFY(m_type)
ARRAY_ALL(byte);
ARRAY_ALL(int);
ARRAY_ALL(long);
ARRAY_ALL(float);
ARRAY_ALL(double);
ARRAY_ALL(string);
ARRAY_ALL(Color);
ARRAY_ALL(Vector2);
ARRAY_ALL(Vector2i);
ARRAY_ALL(Vector3);
ARRAY_ALL(Vector3i);
ARRAY_ALL(Vector4);
ARRAY_ALL(Vector4i);
#undef ARRAY_ALL
#undef ARRAY_IS_EMPTY
#undef ARRAY_JOIN
#undef ARRAY_STRINGIFY
p_output.append(CLOSE_BLOCK); // End of GD class.
}
void BindingsGenerator::_generate_global_constants(StringBuilder &p_output) {
// Constants (in partial GD class)
p_output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
p_output.append("\n#pragma warning disable CS1591 // Disable warning: "
"'Missing XML comment for publicly visible type or member'\n");
p_output.append("public static partial class " BINDINGS_GLOBAL_SCOPE_CLASS "\n{");
for (const ConstantInterface &iconstant : global_constants) {
if (iconstant.const_doc && iconstant.const_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
p_output.append(INDENT1 "/// </summary>");
}
}
p_output.append(MEMBER_BEGIN "public const long ");
p_output.append(iconstant.proxy_name);
p_output.append(" = ");
p_output.append(itos(iconstant.value));
p_output.append(";");
}
if (!global_constants.is_empty()) {
p_output.append("\n");
}
p_output.append(CLOSE_BLOCK); // end of GD class
// Enums
for (const EnumInterface &ienum : global_enums) {
CRASH_COND(ienum.constants.is_empty());
String enum_proxy_name = ienum.cname.operator String();
bool enum_in_static_class = false;
if (enum_proxy_name.find(".") > 0) {
enum_in_static_class = true;
String enum_class_name = enum_proxy_name.get_slicec('.', 0);
enum_proxy_name = enum_proxy_name.get_slicec('.', 1);
CRASH_COND(enum_class_name != "Variant"); // Hard-coded...
_log("Declaring global enum '%s' inside struct '%s'\n", enum_proxy_name.utf8().get_data(), enum_class_name.utf8().get_data());
p_output.append("\npublic partial struct ");
p_output.append(enum_class_name);
p_output.append("\n" OPEN_BLOCK);
}
if (ienum.is_flags) {
p_output.append("\n[System.Flags]");
}
p_output.append("\npublic enum ");
p_output.append(enum_proxy_name);
p_output.append(" : long");
p_output.append("\n" OPEN_BLOCK);
const ConstantInterface &last = ienum.constants.back()->get();
for (const ConstantInterface &iconstant : ienum.constants) {
if (iconstant.const_doc && iconstant.const_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), nullptr);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
p_output.append(INDENT1 "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
p_output.append(INDENT1 "/// </summary>\n");
}
}
p_output.append(INDENT1);
p_output.append(iconstant.proxy_name);
p_output.append(" = ");
p_output.append(itos(iconstant.value));
p_output.append(&iconstant != &last ? ",\n" : "\n");
}
p_output.append(CLOSE_BLOCK);
if (enum_in_static_class) {
p_output.append(CLOSE_BLOCK);
}
}
p_output.append("\n#pragma warning restore CS1591\n");
}
Error BindingsGenerator::generate_cs_core_project(const String &p_proj_dir) {
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
if (!DirAccess::exists(p_proj_dir)) {
Error err = da->make_dir_recursive(p_proj_dir);
ERR_FAIL_COND_V_MSG(err != OK, ERR_CANT_CREATE, "Cannot create directory '" + p_proj_dir + "'.");
}
da->change_dir(p_proj_dir);
da->make_dir("Generated");
da->make_dir("Generated/GodotObjects");
String base_gen_dir = path::join(p_proj_dir, "Generated");
String godot_objects_gen_dir = path::join(base_gen_dir, "GodotObjects");
Vector<String> compile_items;
// Generate source file for global scope constants and enums
{
StringBuilder constants_source;
_generate_global_constants(constants_source);
String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_constants.cs");
Error save_err = _save_file(output_file, constants_source);
if (save_err != OK) {
return save_err;
}
compile_items.push_back(output_file);
}
// Generate source file for array extensions
{
StringBuilder extensions_source;
_generate_array_extensions(extensions_source);
String output_file = path::join(base_gen_dir, BINDINGS_GLOBAL_SCOPE_CLASS "_extensions.cs");
Error save_err = _save_file(output_file, extensions_source);
if (save_err != OK) {
return save_err;
}
compile_items.push_back(output_file);
}
for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
const TypeInterface &itype = E.value;
if (itype.api_type == ClassDB::API_EDITOR) {
continue;
}
String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
Error err = _generate_cs_type(itype, output_file);
if (err == ERR_SKIP) {
continue;
}
if (err != OK) {
return err;
}
compile_items.push_back(output_file);
}
// Generate native calls
StringBuilder cs_icalls_content;
cs_icalls_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
cs_icalls_content.append("using System;\n"
"using System.Diagnostics.CodeAnalysis;\n"
"using System.Runtime.InteropServices;\n"
"using Godot.NativeInterop;\n"
"\n");
cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n");
cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantUnsafeContext\")]\n");
cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantNameQualifier\")]\n");
cs_icalls_content.append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
cs_icalls_content.append("internal static class " BINDINGS_CLASS_NATIVECALLS "\n{");
cs_icalls_content.append(MEMBER_BEGIN "internal static ulong godot_api_hash = ");
cs_icalls_content.append(String::num_uint64(ClassDB::get_api_hash(ClassDB::API_CORE)) + ";\n");
cs_icalls_content.append(MEMBER_BEGIN "private const int VarArgsSpanThreshold = 10;\n");
for (const InternalCall &icall : method_icalls) {
if (icall.editor_only) {
continue;
}
Error err = _generate_cs_native_calls(icall, cs_icalls_content);
if (err != OK) {
return err;
}
}
cs_icalls_content.append(CLOSE_BLOCK);
String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS ".cs");
Error err = _save_file(internal_methods_file, cs_icalls_content);
if (err != OK) {
return err;
}
compile_items.push_back(internal_methods_file);
// Generate GeneratedIncludes.props
StringBuilder includes_props_content;
includes_props_content.append("<Project>\n"
" <ItemGroup>\n");
for (int i = 0; i < compile_items.size(); i++) {
String include = path::relative_to(compile_items[i], p_proj_dir).replace("/", "\\");
includes_props_content.append(" <Compile Include=\"" + include + "\" />\n");
}
includes_props_content.append(" </ItemGroup>\n"
"</Project>\n");
String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
err = _save_file(includes_props_file, includes_props_content);
if (err != OK) {
return err;
}
return OK;
}
Error BindingsGenerator::generate_cs_editor_project(const String &p_proj_dir) {
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
if (!DirAccess::exists(p_proj_dir)) {
Error err = da->make_dir_recursive(p_proj_dir);
ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
}
da->change_dir(p_proj_dir);
da->make_dir("Generated");
da->make_dir("Generated/GodotObjects");
String base_gen_dir = path::join(p_proj_dir, "Generated");
String godot_objects_gen_dir = path::join(base_gen_dir, "GodotObjects");
Vector<String> compile_items;
for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
const TypeInterface &itype = E.value;
if (itype.api_type != ClassDB::API_EDITOR) {
continue;
}
String output_file = path::join(godot_objects_gen_dir, itype.proxy_name + ".cs");
Error err = _generate_cs_type(itype, output_file);
if (err == ERR_SKIP) {
continue;
}
if (err != OK) {
return err;
}
compile_items.push_back(output_file);
}
// Generate native calls
StringBuilder cs_icalls_content;
cs_icalls_content.append("namespace " BINDINGS_NAMESPACE ";\n\n");
cs_icalls_content.append("using System;\n"
"using System.Diagnostics.CodeAnalysis;\n"
"using System.Runtime.InteropServices;\n"
"using Godot.NativeInterop;\n"
"\n");
cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"InconsistentNaming\")]\n");
cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantUnsafeContext\")]\n");
cs_icalls_content.append("[SuppressMessage(\"ReSharper\", \"RedundantNameQualifier\")]\n");
cs_icalls_content.append("[System.Runtime.CompilerServices.SkipLocalsInit]\n");
cs_icalls_content.append("internal static class " BINDINGS_CLASS_NATIVECALLS_EDITOR "\n" OPEN_BLOCK);
cs_icalls_content.append(INDENT1 "internal static ulong godot_api_hash = ");
cs_icalls_content.append(String::num_uint64(ClassDB::get_api_hash(ClassDB::API_EDITOR)) + ";\n");
cs_icalls_content.append(MEMBER_BEGIN "private const int VarArgsSpanThreshold = 10;\n");
cs_icalls_content.append("\n");
for (const InternalCall &icall : method_icalls) {
if (!icall.editor_only) {
continue;
}
Error err = _generate_cs_native_calls(icall, cs_icalls_content);
if (err != OK) {
return err;
}
}
cs_icalls_content.append(CLOSE_BLOCK);
String internal_methods_file = path::join(base_gen_dir, BINDINGS_CLASS_NATIVECALLS_EDITOR ".cs");
Error err = _save_file(internal_methods_file, cs_icalls_content);
if (err != OK) {
return err;
}
compile_items.push_back(internal_methods_file);
// Generate GeneratedIncludes.props
StringBuilder includes_props_content;
includes_props_content.append("<Project>\n"
" <ItemGroup>\n");
for (int i = 0; i < compile_items.size(); i++) {
String include = path::relative_to(compile_items[i], p_proj_dir).replace("/", "\\");
includes_props_content.append(" <Compile Include=\"" + include + "\" />\n");
}
includes_props_content.append(" </ItemGroup>\n"
"</Project>\n");
String includes_props_file = path::join(base_gen_dir, "GeneratedIncludes.props");
err = _save_file(includes_props_file, includes_props_content);
if (err != OK) {
return err;
}
return OK;
}
Error BindingsGenerator::generate_cs_api(const String &p_output_dir) {
ERR_FAIL_COND_V(!initialized, ERR_UNCONFIGURED);
String output_dir = path::abspath(path::realpath(p_output_dir));
Ref<DirAccess> da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
ERR_FAIL_COND_V(da.is_null(), ERR_CANT_CREATE);
if (!DirAccess::exists(output_dir)) {
Error err = da->make_dir_recursive(output_dir);
ERR_FAIL_COND_V(err != OK, ERR_CANT_CREATE);
}
Error proj_err;
// Generate GodotSharp source files
String core_proj_dir = output_dir.plus_file(CORE_API_ASSEMBLY_NAME);
proj_err = generate_cs_core_project(core_proj_dir);
if (proj_err != OK) {
ERR_PRINT("Generation of the Core API C# project failed.");
return proj_err;
}
// Generate GodotSharpEditor source files
String editor_proj_dir = output_dir.plus_file(EDITOR_API_ASSEMBLY_NAME);
proj_err = generate_cs_editor_project(editor_proj_dir);
if (proj_err != OK) {
ERR_PRINT("Generation of the Editor API C# project failed.");
return proj_err;
}
_log("The Godot API sources were successfully generated\n");
return OK;
}
// FIXME: There are some members that hide other inherited members.
// - In the case of both members being the same kind, the new one must be declared
// explicitly as 'new' to avoid the warning (and we must print a message about it).
// - In the case of both members being of a different kind, then the new one must
// be renamed to avoid the name collision (and we must print a warning about it).
// - Csc warning e.g.:
// ObjectType/LineEdit.cs(140,38): warning CS0108: 'LineEdit.FocusMode' hides inherited member 'Control.FocusMode'. Use the new keyword if hiding was intended.
Error BindingsGenerator::_generate_cs_type(const TypeInterface &itype, const String &p_output_file) {
CRASH_COND(!itype.is_object_type);
bool is_derived_type = itype.base_name != StringName();
if (!is_derived_type) {
// Some Godot.Object assertions
CRASH_COND(itype.cname != name_cache.type_Object);
CRASH_COND(!itype.is_instantiable);
CRASH_COND(itype.api_type != ClassDB::API_CORE);
CRASH_COND(itype.is_ref_counted);
CRASH_COND(itype.is_singleton);
}
_log("Generating %s.cs...\n", itype.proxy_name.utf8().get_data());
StringBuilder output;
output.append("namespace " BINDINGS_NAMESPACE ";\n\n");
output.append("using System;\n"); // IntPtr
output.append("using System.Diagnostics;\n"); // DebuggerBrowsable
output.append("using Godot.NativeInterop;\n");
output.append("\n"
"#pragma warning disable CS1591 // Disable warning: "
"'Missing XML comment for publicly visible type or member'\n"
"#pragma warning disable CS1573 // Disable warning: "
"'Parameter has no matching param tag in the XML comment'\n");
output.append("\n#nullable disable\n");
const DocData::ClassDoc *class_doc = itype.class_doc;
if (class_doc && class_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(class_doc->description), &itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
output.append("/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
output.append("/// ");
output.append(summary_lines[i]);
output.append("\n");
}
output.append("/// </summary>\n");
}
}
// We generate a `GodotClassName` attribute if the engine class name is not the same as the
// generated C# class name. This allows introspection code to find the name associated with
// the class. If the attribute is not present, the C# class name can be used instead.
if (itype.name != itype.proxy_name) {
output << "[GodotClassName(\"" << itype.name << "\")]\n";
}
output.append("public ");
if (itype.is_singleton) {
output.append("static partial class ");
} else {
// Even if the class is not instantiable, we can't declare it abstract because
// the engine can still instantiate them and return them via the scripting API.
// Example: `SceneTreeTimer` returned from `SceneTree.create_timer`.
// See the reverted commit: ef5672d3f94a7321ed779c922088bb72adbb1521
output.append("partial class ");
}
output.append(itype.proxy_name);
if (is_derived_type && !itype.is_singleton) {
if (obj_types.has(itype.base_name)) {
output.append(" : ");
output.append(obj_types[itype.base_name].proxy_name);
} else {
ERR_PRINT("Base type '" + itype.base_name.operator String() + "' does not exist, for class '" + itype.name + "'.");
return ERR_INVALID_DATA;
}
}
output.append("\n{");
// Add constants
for (const ConstantInterface &iconstant : itype.constants) {
if (iconstant.const_doc && iconstant.const_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
output.append(INDENT1 "/// ");
output.append(summary_lines[i]);
output.append("\n");
}
output.append(INDENT1 "/// </summary>");
}
}
output.append(MEMBER_BEGIN "public const long ");
output.append(iconstant.proxy_name);
output.append(" = ");
output.append(itos(iconstant.value));
output.append(";");
}
if (itype.constants.size()) {
output.append("\n");
}
// Add enums
for (const EnumInterface &ienum : itype.enums) {
ERR_FAIL_COND_V(ienum.constants.is_empty(), ERR_BUG);
if (ienum.is_flags) {
output.append(MEMBER_BEGIN "[System.Flags]");
}
output.append(MEMBER_BEGIN "public enum ");
output.append(ienum.cname.operator String());
output.append(" : long");
output.append(MEMBER_BEGIN OPEN_BLOCK);
const ConstantInterface &last = ienum.constants.back()->get();
for (const ConstantInterface &iconstant : ienum.constants) {
if (iconstant.const_doc && iconstant.const_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(iconstant.const_doc->description), &itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
output.append(INDENT2 "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
output.append(INDENT2 "/// ");
output.append(summary_lines[i]);
output.append("\n");
}
output.append(INDENT2 "/// </summary>\n");
}
}
output.append(INDENT2);
output.append(iconstant.proxy_name);
output.append(" = ");
output.append(itos(iconstant.value));
output.append(&iconstant != &last ? ",\n" : "\n");
}
output.append(INDENT1 CLOSE_BLOCK);
}
// Add properties
for (const PropertyInterface &iprop : itype.properties) {
Error prop_err = _generate_cs_property(itype, iprop, output);
ERR_FAIL_COND_V_MSG(prop_err != OK, prop_err,
"Failed to generate property '" + iprop.cname.operator String() +
"' for class '" + itype.name + "'.");
}
if (itype.is_singleton) {
// Add the type name and the singleton pointer as static fields
output.append(MEMBER_BEGIN "private static Godot.Object singleton;\n");
output << MEMBER_BEGIN "public static Godot.Object " CS_PROPERTY_SINGLETON "\n" INDENT1 "{\n"
<< INDENT2 "get\n" INDENT2 "{\n" INDENT3 "if (singleton == null)\n"
<< INDENT4 "singleton = " C_METHOD_ENGINE_GET_SINGLETON "(typeof("
<< itype.proxy_name
<< ").Name);\n" INDENT3 "return singleton;\n" INDENT2 "}\n" INDENT1 "}\n";
output.append(MEMBER_BEGIN "private static readonly StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
output.append(itype.name);
output.append("\";\n");
} else {
// IMPORTANT: We also generate the static fields for Godot.Object instead of declaring
// them manually in the `Object.base.cs` partial class declaration, because they're
// required by other static fields in this generated partial class declaration.
// Static fields are initialized in order of declaration, but when they're in different
// partial class declarations then it becomes harder to tell (Rider warns about this).
// Add native name static field
if (is_derived_type) {
output << MEMBER_BEGIN "private static readonly System.Type CachedType = typeof(" << itype.proxy_name << ");\n";
}
output.append(MEMBER_BEGIN "private static readonly StringName " BINDINGS_NATIVE_NAME_FIELD " = \"");
output.append(itype.name);
output.append("\";\n");
if (itype.is_instantiable) {
// Add native constructor static field
output << MEMBER_BEGIN << "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
<< INDENT1 "private static readonly unsafe delegate* unmanaged<IntPtr> "
<< CS_STATIC_FIELD_NATIVE_CTOR " = " ICALL_CLASSDB_GET_CONSTRUCTOR
<< "(" BINDINGS_NATIVE_NAME_FIELD ");\n";
}
if (is_derived_type) {
// Add default constructor
if (itype.is_instantiable) {
output << MEMBER_BEGIN "public " << itype.proxy_name << "() : this("
<< (itype.memory_own ? "true" : "false") << ")\n" OPEN_BLOCK_L1
<< INDENT2 "unsafe\n" INDENT2 OPEN_BLOCK
<< INDENT3 "_ConstructAndInitialize(" CS_STATIC_FIELD_NATIVE_CTOR ", "
<< BINDINGS_NATIVE_NAME_FIELD ", CachedType, refCounted: "
<< (itype.is_ref_counted ? "true" : "false") << ");\n"
<< CLOSE_BLOCK_L2 CLOSE_BLOCK_L1;
} else {
// Hide the constructor
output.append(MEMBER_BEGIN "internal ");
output.append(itype.proxy_name);
output.append("() {}\n");
}
// Add.. em.. trick constructor. Sort of.
output.append(MEMBER_BEGIN "internal ");
output.append(itype.proxy_name);
output.append("(bool " CS_PARAM_MEMORYOWN ") : base(" CS_PARAM_MEMORYOWN ") {}\n");
}
}
// Methods
int method_bind_count = 0;
for (const MethodInterface &imethod : itype.methods) {
Error method_err = _generate_cs_method(itype, imethod, method_bind_count, output);
ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
"Failed to generate method '" + imethod.name + "' for class '" + itype.name + "'.");
}
// Signals
for (const SignalInterface &isignal : itype.signals_) {
Error method_err = _generate_cs_signal(itype, isignal, output);
ERR_FAIL_COND_V_MSG(method_err != OK, method_err,
"Failed to generate signal '" + isignal.name + "' for class '" + itype.name + "'.");
}
// Script members look-up
if (!itype.is_singleton && (is_derived_type || itype.has_virtual_methods)) {
// Generate method names cache fields
for (const MethodInterface &imethod : itype.methods) {
if (!imethod.is_virtual) {
continue;
}
output << MEMBER_BEGIN "// ReSharper disable once InconsistentNaming\n"
<< INDENT1 "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
<< INDENT1 "private static readonly StringName "
<< CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
<< " = \"" << imethod.proxy_name << "\";\n";
}
// TODO: Only generate HasGodotClassMethod and InvokeGodotClassMethod if there's any method
// Generate InvokeGodotClassMethod
output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual")
<< " bool " CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(in godot_string_name method, "
<< "NativeVariantPtrArgs args, int argCount, out godot_variant ret)\n"
<< INDENT1 "{\n";
for (const MethodInterface &imethod : itype.methods) {
if (!imethod.is_virtual) {
continue;
}
// We also call HasGodotClassMethod to ensure the method is overridden and avoid calling
// the stub implementation. This solution adds some extra overhead to calls, but it's
// much simpler than other solutions. This won't be a problem once we move to function
// pointers of generated wrappers for each method, as lookup will only happen once.
// We check both native names (snake_case) and proxy names (PascalCase)
output << INDENT2 "if ((method == " << CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
<< " || method == MethodName." << imethod.proxy_name
<< ") && argCount == " << itos(imethod.arguments.size())
<< " && " << CS_METHOD_HAS_GODOT_CLASS_METHOD << "((godot_string_name)"
<< CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name << ".NativeValue))\n"
<< INDENT2 "{\n";
if (imethod.return_type.cname != name_cache.type_void) {
output << INDENT3 "var callRet = ";
} else {
output << INDENT3;
}
output << imethod.proxy_name << "(";
for (int i = 0; i < imethod.arguments.size(); i++) {
const ArgumentInterface &iarg = imethod.arguments[i];
const TypeInterface *arg_type = _get_type_or_null(iarg.type);
ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
if (i != 0) {
output << ", ";
}
if (arg_type->cname == name_cache.type_Array_generic || arg_type->cname == name_cache.type_Dictionary_generic) {
String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
output << "new " << arg_cs_type << "(" << sformat(arg_type->cs_variant_to_managed, "args[" + itos(i) + "]", arg_type->cs_type, arg_type->name) << ")";
} else {
output << sformat(arg_type->cs_variant_to_managed,
"args[" + itos(i) + "]", arg_type->cs_type, arg_type->name);
}
}
output << ");\n";
if (imethod.return_type.cname != name_cache.type_void) {
const TypeInterface *return_type = _get_type_or_null(imethod.return_type);
ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
output << INDENT3 "ret = "
<< sformat(return_type->cs_managed_to_variant, "callRet", return_type->cs_type, return_type->name)
<< ";\n"
<< INDENT3 "return true;\n";
} else {
output << INDENT3 "ret = default;\n"
<< INDENT3 "return true;\n";
}
output << INDENT2 "}\n";
}
if (is_derived_type) {
output << INDENT2 "return base." CS_METHOD_INVOKE_GODOT_CLASS_METHOD "(method, args, argCount, out ret);\n";
} else {
output << INDENT2 "ret = default;\n"
<< INDENT2 "return false;\n";
}
output << INDENT1 "}\n";
// Generate HasGodotClassMethod
output << MEMBER_BEGIN "protected internal " << (is_derived_type ? "override" : "virtual")
<< " bool " CS_METHOD_HAS_GODOT_CLASS_METHOD "(in godot_string_name method)\n"
<< INDENT1 "{\n";
for (const MethodInterface &imethod : itype.methods) {
if (!imethod.is_virtual) {
continue;
}
// We check for native names (snake_case). If we detect one, we call HasGodotClassMethod
// again, but this time with the respective proxy name (PascalCase). It's the job of
// user derived classes to override the method and check for those. Our C# source
// generators take care of generating those override methods.
output << INDENT2 "if (method == MethodName." << imethod.proxy_name
<< ")\n" INDENT2 "{\n"
<< INDENT3 "if (" CS_METHOD_HAS_GODOT_CLASS_METHOD "("
<< CS_STATIC_FIELD_METHOD_PROXY_NAME_PREFIX << imethod.name
<< ".NativeValue.DangerousSelfRef))\n" INDENT3 "{\n"
<< INDENT4 "return true;\n"
<< INDENT3 "}\n" INDENT2 "}\n";
}
if (is_derived_type) {
output << INDENT2 "return base." CS_METHOD_HAS_GODOT_CLASS_METHOD "(method);\n";
} else {
output << INDENT2 "return false;\n";
}
output << INDENT1 "}\n";
}
//Generate StringName for all class members
bool is_inherit = !itype.is_singleton && obj_types.has(itype.base_name);
//PropertyName
if (is_inherit) {
output << MEMBER_BEGIN "public new class PropertyName : " << obj_types[itype.base_name].proxy_name << ".PropertyName";
} else {
output << MEMBER_BEGIN "public class PropertyName";
}
output << "\n"
<< INDENT1 "{\n";
for (const PropertyInterface &iprop : itype.properties) {
output << INDENT2 "public static readonly StringName " << iprop.proxy_name << " = \"" << iprop.cname << "\";\n";
}
output << INDENT1 "}\n";
//MethodName
if (is_inherit) {
output << MEMBER_BEGIN "public new class MethodName : " << obj_types[itype.base_name].proxy_name << ".MethodName";
} else {
output << MEMBER_BEGIN "public class MethodName";
}
output << "\n"
<< INDENT1 "{\n";
for (const MethodInterface &imethod : itype.methods) {
output << INDENT2 "public static readonly StringName " << imethod.proxy_name << " = \"" << imethod.cname << "\";\n";
}
output << INDENT1 "}\n";
//SignalName
if (is_inherit) {
output << MEMBER_BEGIN "public new class SignalName : " << obj_types[itype.base_name].proxy_name << ".SignalName";
} else {
output << MEMBER_BEGIN "public class SignalName";
}
output << "\n"
<< INDENT1 "{\n";
for (const SignalInterface &isignal : itype.signals_) {
output << INDENT2 "public static readonly StringName " << isignal.proxy_name << " = \"" << isignal.cname << "\";\n";
}
output << INDENT1 "}\n";
output.append(CLOSE_BLOCK /* class */);
output.append("\n"
"#pragma warning restore CS1591\n"
"#pragma warning restore CS1573\n");
return _save_file(p_output_file, output);
}
Error BindingsGenerator::_generate_cs_property(const BindingsGenerator::TypeInterface &p_itype, const PropertyInterface &p_iprop, StringBuilder &p_output) {
const MethodInterface *setter = p_itype.find_method_by_name(p_iprop.setter);
// Search it in base types too
const TypeInterface *current_type = &p_itype;
while (!setter && current_type->base_name != StringName()) {
HashMap<StringName, TypeInterface>::Iterator base_match = obj_types.find(current_type->base_name);
ERR_FAIL_COND_V_MSG(!base_match, ERR_BUG, "Type not found '" + current_type->base_name + "'. Inherited by '" + current_type->name + "'.");
current_type = &base_match->value;
setter = current_type->find_method_by_name(p_iprop.setter);
}
const MethodInterface *getter = p_itype.find_method_by_name(p_iprop.getter);
// Search it in base types too
current_type = &p_itype;
while (!getter && current_type->base_name != StringName()) {
HashMap<StringName, TypeInterface>::Iterator base_match = obj_types.find(current_type->base_name);
ERR_FAIL_COND_V_MSG(!base_match, ERR_BUG, "Type not found '" + current_type->base_name + "'. Inherited by '" + current_type->name + "'.");
current_type = &base_match->value;
getter = current_type->find_method_by_name(p_iprop.getter);
}
ERR_FAIL_COND_V(!setter && !getter, ERR_BUG);
if (setter) {
int setter_argc = p_iprop.index != -1 ? 2 : 1;
ERR_FAIL_COND_V(setter->arguments.size() != setter_argc, ERR_BUG);
}
if (getter) {
int getter_argc = p_iprop.index != -1 ? 1 : 0;
ERR_FAIL_COND_V(getter->arguments.size() != getter_argc, ERR_BUG);
}
if (getter && setter) {
const ArgumentInterface &setter_first_arg = setter->arguments.back()->get();
if (getter->return_type.cname != setter_first_arg.type.cname) {
// Special case for Node::set_name
bool whitelisted = getter->return_type.cname == name_cache.type_StringName &&
setter_first_arg.type.cname == name_cache.type_String;
ERR_FAIL_COND_V_MSG(!whitelisted, ERR_BUG,
"Return type from getter doesn't match first argument of setter for property: '" +
p_itype.name + "." + String(p_iprop.cname) + "'.");
}
}
const TypeReference &proptype_name = getter ? getter->return_type : setter->arguments.back()->get().type;
const TypeInterface *prop_itype = _get_type_or_null(proptype_name);
ERR_FAIL_NULL_V(prop_itype, ERR_BUG); // Property type not found
ERR_FAIL_COND_V_MSG(prop_itype->is_singleton, ERR_BUG,
"Property type is a singleton: '" + p_itype.name + "." + String(p_iprop.cname) + "'.");
if (p_itype.api_type == ClassDB::API_CORE) {
ERR_FAIL_COND_V_MSG(prop_itype->api_type == ClassDB::API_EDITOR, ERR_BUG,
"Property '" + p_itype.name + "." + String(p_iprop.cname) + "' has type '" + prop_itype->name +
"' from the editor API. Core API cannot have dependencies on the editor API.");
}
if (p_iprop.prop_doc && p_iprop.prop_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(p_iprop.prop_doc->description), &p_itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
p_output.append(INDENT1 "/// </summary>");
}
}
p_output.append(MEMBER_BEGIN "public ");
if (p_itype.is_singleton) {
p_output.append("static ");
}
String prop_cs_type = prop_itype->cs_type + _get_generic_type_parameters(*prop_itype, proptype_name.generic_type_parameters);
p_output.append(prop_cs_type);
p_output.append(" ");
p_output.append(p_iprop.proxy_name);
p_output.append("\n" OPEN_BLOCK_L1);
if (getter) {
p_output.append(INDENT2 "get\n"
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning disable CS0618 // Disable warning about obsolete method\n"
OPEN_BLOCK_L2 INDENT3);
p_output.append("return ");
p_output.append(getter->proxy_name + "(");
if (p_iprop.index != -1) {
const ArgumentInterface &idx_arg = getter->arguments.front()->get();
if (idx_arg.type.cname != name_cache.type_int) {
// Assume the index parameter is an enum
const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
CRASH_COND(idx_arg_type == nullptr);
p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index));
} else {
p_output.append(itos(p_iprop.index));
}
}
p_output.append(");\n"
CLOSE_BLOCK_L2
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning restore CS0618\n");
}
if (setter) {
p_output.append(INDENT2 "set\n"
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning disable CS0618 // Disable warning about obsolete method\n"
OPEN_BLOCK_L2 INDENT3);
p_output.append(setter->proxy_name + "(");
if (p_iprop.index != -1) {
const ArgumentInterface &idx_arg = setter->arguments.front()->get();
if (idx_arg.type.cname != name_cache.type_int) {
// Assume the index parameter is an enum
const TypeInterface *idx_arg_type = _get_type_or_null(idx_arg.type);
CRASH_COND(idx_arg_type == nullptr);
p_output.append("(" + idx_arg_type->proxy_name + ")" + itos(p_iprop.index) + ", ");
} else {
p_output.append(itos(p_iprop.index) + ", ");
}
}
p_output.append("value);\n"
CLOSE_BLOCK_L2
// TODO Remove this once we make accessor methods private/internal (they will no longer be marked as obsolete after that)
"#pragma warning restore CS0618\n");
}
p_output.append(CLOSE_BLOCK_L1);
return OK;
}
Error BindingsGenerator::_generate_cs_method(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::MethodInterface &p_imethod, int &p_method_bind_count, StringBuilder &p_output) {
const TypeInterface *return_type = _get_type_or_null(p_imethod.return_type);
ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
ERR_FAIL_COND_V_MSG(return_type->is_singleton, ERR_BUG,
"Method return type is a singleton: '" + p_itype.name + "." + p_imethod.name + "'.");
if (p_itype.api_type == ClassDB::API_CORE) {
ERR_FAIL_COND_V_MSG(return_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
"Method '" + p_itype.name + "." + p_imethod.name + "' has return type '" + return_type->name +
"' from the editor API. Core API cannot have dependencies on the editor API.");
}
String method_bind_field = CS_STATIC_FIELD_METHOD_BIND_PREFIX + itos(p_method_bind_count);
String arguments_sig;
StringBuilder cs_in_statements;
bool cs_in_expr_is_unsafe = false;
String icall_params = method_bind_field;
if (!p_imethod.is_static) {
if (p_itype.cs_in.size()) {
cs_in_statements << sformat(p_itype.cs_in, p_itype.c_type, "this",
String(), String(), String(), INDENT2);
}
icall_params += ", " + sformat(p_itype.cs_in_expr, "this");
}
StringBuilder default_args_doc;
// Retrieve information from the arguments
const ArgumentInterface &first = p_imethod.arguments.front()->get();
for (const ArgumentInterface &iarg : p_imethod.arguments) {
const TypeInterface *arg_type = _get_type_or_null(iarg.type);
ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
"Argument type is a singleton: '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
if (p_itype.api_type == ClassDB::API_CORE) {
ERR_FAIL_COND_V_MSG(arg_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
"Argument '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "' has type '" +
arg_type->name + "' from the editor API. Core API cannot have dependencies on the editor API.");
}
if (iarg.default_argument.size()) {
CRASH_COND_MSG(!_arg_default_value_is_assignable_to_type(iarg.def_param_value, *arg_type),
"Invalid default value for parameter '" + iarg.name + "' of method '" + p_itype.name + "." + p_imethod.name + "'.");
}
String arg_cs_type = arg_type->cs_type + _get_generic_type_parameters(*arg_type, iarg.type.generic_type_parameters);
// Add the current arguments to the signature
// If the argument has a default value which is not a constant, we will make it Nullable
{
if (&iarg != &first) {
arguments_sig += ", ";
}
if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
arguments_sig += "Nullable<";
}
arguments_sig += arg_cs_type;
if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
arguments_sig += "> ";
} else {
arguments_sig += " ";
}
arguments_sig += iarg.name;
if (iarg.default_argument.size()) {
if (iarg.def_param_mode != ArgumentInterface::CONSTANT) {
arguments_sig += " = null";
} else {
arguments_sig += " = " + sformat(iarg.default_argument, arg_type->cs_type);
}
}
}
icall_params += ", ";
if (iarg.default_argument.size() && iarg.def_param_mode != ArgumentInterface::CONSTANT) {
// The default value of an argument must be constant. Otherwise we make it Nullable and do the following:
// Type arg_in = arg.HasValue ? arg.Value : <non-const default value>;
String arg_or_defval_local = iarg.name;
arg_or_defval_local += "OrDefVal";
cs_in_statements << INDENT2 << arg_cs_type << " " << arg_or_defval_local << " = " << iarg.name;
if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
cs_in_statements << ".HasValue ? ";
} else {
cs_in_statements << " != null ? ";
}
cs_in_statements << iarg.name;
if (iarg.def_param_mode == ArgumentInterface::NULLABLE_VAL) {
cs_in_statements << ".Value : ";
} else {
cs_in_statements << " : ";
}
String cs_type = arg_cs_type;
if (cs_type.ends_with("[]")) {
cs_type = cs_type.substr(0, cs_type.length() - 2);
}
String def_arg = sformat(iarg.default_argument, cs_type);
cs_in_statements << def_arg << ";\n";
if (arg_type->cs_in.size()) {
cs_in_statements << sformat(arg_type->cs_in, arg_type->c_type, arg_or_defval_local,
String(), String(), String(), INDENT2);
}
if (arg_type->cs_in_expr.is_empty()) {
icall_params += arg_or_defval_local;
} else {
icall_params += sformat(arg_type->cs_in_expr, arg_or_defval_local, arg_type->c_type);
}
// Apparently the name attribute must not include the @
String param_tag_name = iarg.name.begins_with("@") ? iarg.name.substr(1, iarg.name.length()) : iarg.name;
// Escape < and > in the attribute default value
String param_def_arg = def_arg.replacen("<", "<").replacen(">", ">");
default_args_doc.append(MEMBER_BEGIN "/// <param name=\"" + param_tag_name + "\">If the parameter is null, then the default value is <c>" + param_def_arg + "</c>.</param>");
} else {
if (arg_type->cs_in.size()) {
cs_in_statements << sformat(arg_type->cs_in, arg_type->c_type, iarg.name,
String(), String(), String(), INDENT2);
}
icall_params += arg_type->cs_in_expr.is_empty() ? iarg.name : sformat(arg_type->cs_in_expr, iarg.name, arg_type->c_type);
}
cs_in_expr_is_unsafe |= arg_type->cs_in_expr_is_unsafe;
}
// Generate method
{
if (!p_imethod.is_virtual && !p_imethod.requires_object_call) {
p_output << MEMBER_BEGIN "[DebuggerBrowsable(DebuggerBrowsableState.Never)]\n"
<< INDENT1 "private static readonly IntPtr " << method_bind_field << " = ";
if (p_itype.is_singleton) {
// Singletons are static classes. They don't derive Godot.Object,
// so we need to specify the type to call the static method.
p_output << "Object.";
}
p_output << ICALL_CLASSDB_GET_METHOD "(" BINDINGS_NATIVE_NAME_FIELD ", MethodName."
<< p_imethod.proxy_name
<< ");\n";
}
if (p_imethod.method_doc && p_imethod.method_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(p_imethod.method_doc->description), &p_itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
p_output.append(INDENT1 "/// </summary>");
}
}
if (default_args_doc.get_string_length()) {
p_output.append(default_args_doc.as_string());
}
if (p_imethod.is_deprecated) {
if (p_imethod.deprecation_message.is_empty()) {
WARN_PRINT("An empty deprecation message is discouraged. Method: '" + p_imethod.proxy_name + "'.");
}
p_output.append(MEMBER_BEGIN "[Obsolete(\"");
p_output.append(p_imethod.deprecation_message);
p_output.append("\")]");
}
p_output.append(MEMBER_BEGIN);
p_output.append(p_imethod.is_internal ? "internal " : "public ");
if (p_itype.is_singleton || p_imethod.is_static) {
p_output.append("static ");
} else if (p_imethod.is_virtual) {
p_output.append("virtual ");
}
if (cs_in_expr_is_unsafe) {
p_output.append("unsafe ");
}
String return_cs_type = return_type->cs_type + _get_generic_type_parameters(*return_type, p_imethod.return_type.generic_type_parameters);
p_output.append(return_cs_type + " ");
p_output.append(p_imethod.proxy_name + "(");
p_output.append(arguments_sig + ")\n" OPEN_BLOCK_L1);
if (p_imethod.is_virtual) {
// Godot virtual method must be overridden, therefore we return a default value by default.
if (return_type->cname == name_cache.type_void) {
p_output.append(CLOSE_BLOCK_L1);
} else {
p_output.append(INDENT2 "return default;\n" CLOSE_BLOCK_L1);
}
return OK; // Won't increment method bind count
}
if (p_imethod.requires_object_call) {
// Fallback to Godot's object.Call(string, params)
p_output.append(INDENT2 CS_METHOD_CALL "(\"");
p_output.append(p_imethod.name);
p_output.append("\"");
for (const ArgumentInterface &iarg : p_imethod.arguments) {
p_output.append(", ");
p_output.append(iarg.name);
}
p_output.append(");\n" CLOSE_BLOCK_L1);
return OK; // Won't increment method bind count
}
HashMap<const MethodInterface *, const InternalCall *>::ConstIterator match = method_icalls_map.find(&p_imethod);
ERR_FAIL_NULL_V(match, ERR_BUG);
const InternalCall *im_icall = match->value;
String im_call = im_icall->editor_only ? BINDINGS_CLASS_NATIVECALLS_EDITOR : BINDINGS_CLASS_NATIVECALLS;
im_call += ".";
im_call += im_icall->name;
if (p_imethod.arguments.size() && cs_in_statements.get_string_length() > 0) {
p_output.append(cs_in_statements.as_string());
}
if (return_type->cname == name_cache.type_void) {
p_output << INDENT2 << im_call << "(" << icall_params << ");\n";
} else if (return_type->cs_out.is_empty()) {
p_output << INDENT2 "return " << im_call << "(" << icall_params << ");\n";
} else {
p_output.append(sformat(return_type->cs_out, im_call, icall_params,
return_cs_type, return_type->c_type_out, String(), INDENT2));
p_output.append("\n");
}
p_output.append(CLOSE_BLOCK_L1);
}
p_method_bind_count++;
return OK;
}
Error BindingsGenerator::_generate_cs_signal(const BindingsGenerator::TypeInterface &p_itype, const BindingsGenerator::SignalInterface &p_isignal, StringBuilder &p_output) {
String arguments_sig;
// Retrieve information from the arguments
const ArgumentInterface &first = p_isignal.arguments.front()->get();
for (const ArgumentInterface &iarg : p_isignal.arguments) {
const TypeInterface *arg_type = _get_type_or_null(iarg.type);
ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Argument type not found
ERR_FAIL_COND_V_MSG(arg_type->is_singleton, ERR_BUG,
"Argument type is a singleton: '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "'.");
if (p_itype.api_type == ClassDB::API_CORE) {
ERR_FAIL_COND_V_MSG(arg_type->api_type == ClassDB::API_EDITOR, ERR_BUG,
"Argument '" + iarg.name + "' of signal '" + p_itype.name + "." + p_isignal.name + "' has type '" +
arg_type->name + "' from the editor API. Core API cannot have dependencies on the editor API.");
}
// Add the current arguments to the signature
if (&iarg != &first) {
arguments_sig += ", ";
}
arguments_sig += arg_type->cs_type;
arguments_sig += " ";
arguments_sig += iarg.name;
}
// Generate signal
{
if (p_isignal.method_doc && p_isignal.method_doc->description.size()) {
String xml_summary = bbcode_to_xml(fix_doc_description(p_isignal.method_doc->description), &p_itype);
Vector<String> summary_lines = xml_summary.length() ? xml_summary.split("\n") : Vector<String>();
if (summary_lines.size()) {
p_output.append(MEMBER_BEGIN "/// <summary>\n");
for (int i = 0; i < summary_lines.size(); i++) {
p_output.append(INDENT1 "/// ");
p_output.append(summary_lines[i]);
p_output.append("\n");
}
p_output.append(INDENT1 "/// </summary>");
}
}
if (p_isignal.is_deprecated) {
if (p_isignal.deprecation_message.is_empty()) {
WARN_PRINT("An empty deprecation message is discouraged. Signal: '" + p_isignal.proxy_name + "'.");
}
p_output.append(MEMBER_BEGIN "[Obsolete(\"");
p_output.append(p_isignal.deprecation_message);
p_output.append("\")]");
}
String delegate_name = p_isignal.proxy_name;
delegate_name += "EventHandler"; // Delegate name is [SignalName]EventHandler
// Generate delegate
p_output.append(MEMBER_BEGIN "public delegate void ");
p_output.append(delegate_name);
p_output.append("(");
p_output.append(arguments_sig);
p_output.append(");\n");
// TODO:
// Could we assume the StringName instance of signal name will never be freed (it's stored in ClassDB) before the managed world is unloaded?
// If so, we could store the pointer we get from `data_unique_pointer()` instead of allocating StringName here.
// Generate event
p_output.append(MEMBER_BEGIN "public ");
if (p_itype.is_singleton) {
p_output.append("static ");
}
p_output.append("event ");
p_output.append(delegate_name);
p_output.append(" ");
p_output.append(p_isignal.proxy_name);
p_output.append("\n" OPEN_BLOCK_L1 INDENT2);
if (p_itype.is_singleton) {
p_output.append("add => " CS_PROPERTY_SINGLETON ".Connect(SignalName.");
} else {
p_output.append("add => Connect(SignalName.");
}
p_output.append(p_isignal.proxy_name);
p_output.append(", new Callable(value));\n");
if (p_itype.is_singleton) {
p_output.append(INDENT2 "remove => " CS_PROPERTY_SINGLETON ".Disconnect(SignalName.");
} else {
p_output.append(INDENT2 "remove => Disconnect(SignalName.");
}
p_output.append(p_isignal.proxy_name);
p_output.append(", new Callable(value));\n");
p_output.append(CLOSE_BLOCK_L1);
}
return OK;
}
Error BindingsGenerator::_generate_cs_native_calls(const InternalCall &p_icall, StringBuilder &r_output) {
bool ret_void = p_icall.return_type.cname == name_cache.type_void;
const TypeInterface *return_type = _get_type_or_null(p_icall.return_type);
ERR_FAIL_NULL_V(return_type, ERR_BUG); // Return type not found
StringBuilder c_func_sig;
StringBuilder c_in_statements;
StringBuilder c_args_var_content;
c_func_sig << "IntPtr " CS_PARAM_METHODBIND;
if (!p_icall.is_static) {
c_func_sig += ", IntPtr " CS_PARAM_INSTANCE;
}
// Get arguments information
int i = 0;
for (const TypeReference &arg_type_ref : p_icall.argument_types) {
const TypeInterface *arg_type = _get_type_or_null(arg_type_ref);
ERR_FAIL_NULL_V(arg_type, ERR_BUG); // Return type not found
String c_param_name = "arg" + itos(i + 1);
if (p_icall.is_vararg) {
if (i < p_icall.get_arguments_count() - 1) {
String c_in_vararg = arg_type->c_in_vararg;
if (arg_type->is_object_type) {
c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromGodotObjectPtr(%1);\n";
}
ERR_FAIL_COND_V_MSG(c_in_vararg.is_empty(), ERR_BUG,
"VarArg support not implemented for parameter type: " + arg_type->name);
c_in_statements
<< sformat(c_in_vararg, return_type->c_type, c_param_name,
String(), String(), String(), INDENT3)
<< INDENT3 C_LOCAL_PTRCALL_ARGS "[" << itos(i)
<< "] = new IntPtr(&" << c_param_name << "_in);\n";
}
} else {
if (i > 0) {
c_args_var_content << ", ";
}
if (arg_type->c_in.size()) {
c_in_statements << sformat(arg_type->c_in, arg_type->c_type, c_param_name,
String(), String(), String(), INDENT2);
}
c_args_var_content << sformat(arg_type->c_arg_in, c_param_name);
}
c_func_sig << ", " << arg_type->c_type_in << " " << c_param_name;
i++;
}
String icall_method = p_icall.name;
// Generate icall function
r_output << MEMBER_BEGIN "internal static unsafe " << (ret_void ? "void" : return_type->c_type_out) << " "
<< icall_method << "(" << c_func_sig.as_string() << ") " OPEN_BLOCK;
if (!ret_void && (!p_icall.is_vararg || return_type->cname != name_cache.type_Variant)) {
String ptrcall_return_type;
String initialization;
if (return_type->is_object_type) {
ptrcall_return_type = return_type->is_ref_counted ? "godot_ref" : return_type->c_type;
initialization = " = default";
} else {
ptrcall_return_type = return_type->c_type;
}
r_output << INDENT2;
if (return_type->is_ref_counted || return_type->c_type_is_disposable_struct) {
r_output << "using ";
if (initialization.is_empty()) {
initialization = " = default";
}
} else if (return_type->c_ret_needs_default_initialization) {
initialization = " = default";
}
r_output << ptrcall_return_type << " " C_LOCAL_RET << initialization << ";\n";
}
if (!p_icall.is_static) {
r_output << INDENT2 "if (" CS_PARAM_INSTANCE " == IntPtr.Zero)\n"
<< INDENT3 "throw new ArgumentNullException(nameof(" CS_PARAM_INSTANCE "));\n";
}
String argc_str = itos(p_icall.get_arguments_count());
auto generate_call_and_return_stmts = [&](const char *base_indent) {
if (p_icall.is_vararg) {
// MethodBind Call
r_output << base_indent;
// VarArg methods always return Variant, but there are some cases in which MethodInfo provides
// a specific return type. We trust this information is valid. We need a temporary local to keep
// the Variant alive until the method returns. Otherwise, if the returned Variant holds a RefPtr,
// it could be deleted too early. This is the case with GDScript.new() which returns OBJECT.
// Alternatively, we could just return Variant, but that would result in a worse API.
if (!ret_void) {
if (return_type->cname != name_cache.type_Variant) {
r_output << "using godot_variant " << C_LOCAL_VARARG_RET " = ";
} else {
r_output << "using godot_variant " << C_LOCAL_RET " = ";
}
}
r_output << C_CLASS_NATIVE_FUNCS ".godotsharp_method_bind_call("
<< CS_PARAM_METHODBIND ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
<< ", " << (p_icall.get_arguments_count() ? "(godot_variant**)" C_LOCAL_PTRCALL_ARGS : "null")
<< ", total_length, out _);\n";
if (!ret_void) {
if (return_type->cname != name_cache.type_Variant) {
if (return_type->cname == name_cache.enum_Error) {
r_output << base_indent << C_LOCAL_RET " = VariantUtils.ConvertToInt64(" C_LOCAL_VARARG_RET ");\n";
} else {
// TODO: Use something similar to c_in_vararg (see usage above, with error if not implemented)
CRASH_NOW_MSG("Custom VarArg return type not implemented: " + return_type->name);
r_output << base_indent << C_LOCAL_RET " = " C_LOCAL_VARARG_RET ";\n";
}
}
}
} else {
// MethodBind PtrCall
r_output << base_indent << C_CLASS_NATIVE_FUNCS ".godotsharp_method_bind_ptrcall("
<< CS_PARAM_METHODBIND ", " << (p_icall.is_static ? "IntPtr.Zero" : CS_PARAM_INSTANCE)
<< ", " << (p_icall.get_arguments_count() ? C_LOCAL_PTRCALL_ARGS : "null")
<< ", " << (!ret_void ? "&" C_LOCAL_RET ");\n" : "null);\n");
}
// Return statement
if (!ret_void) {
if (return_type->c_out.is_empty()) {
r_output << base_indent << "return " C_LOCAL_RET ";\n";
} else {
r_output << sformat(return_type->c_out, return_type->c_type_out, C_LOCAL_RET,
return_type->name, String(), String(), base_indent);
}
}
};
if (p_icall.get_arguments_count()) {
if (p_icall.is_vararg) {
String vararg_arg = "arg" + argc_str;
String real_argc_str = itos(p_icall.get_arguments_count() - 1); // Arguments count without vararg
p_icall.get_arguments_count();
r_output << INDENT2 "int vararg_length = " << vararg_arg << ".Length;\n"
<< INDENT2 "int total_length = " << real_argc_str << " + vararg_length;\n";
r_output << INDENT2 "Span<godot_variant.movable> varargs_span = vararg_length <= VarArgsSpanThreshold ?\n"
<< INDENT3 "stackalloc godot_variant.movable[VarArgsSpanThreshold].Cleared() :\n"
<< INDENT3 "new godot_variant.movable[vararg_length];\n";
r_output << INDENT2 "Span<IntPtr> " C_LOCAL_PTRCALL_ARGS "_span = total_length <= VarArgsSpanThreshold ?\n"
<< INDENT3 "stackalloc IntPtr[VarArgsSpanThreshold] :\n"
<< INDENT3 "new IntPtr[total_length];\n";
r_output << INDENT2 "using var variantSpanDisposer = new VariantSpanDisposer(varargs_span);\n";
r_output << INDENT2 "fixed (godot_variant.movable* varargs = &MemoryMarshal.GetReference(varargs_span))\n"
<< INDENT2 "fixed (IntPtr* " C_LOCAL_PTRCALL_ARGS " = "
"&MemoryMarshal.GetReference(" C_LOCAL_PTRCALL_ARGS "_span))\n"
<< OPEN_BLOCK_L2;
r_output << c_in_statements.as_string();
r_output << INDENT3 "for (int i = 0; i < vararg_length; i++) " OPEN_BLOCK
<< INDENT4 "varargs[i] = " << vararg_arg << "[i].NativeVar;\n"
<< INDENT4 C_LOCAL_PTRCALL_ARGS "[" << real_argc_str << " + i] = new IntPtr(&varargs[i]);\n"
<< CLOSE_BLOCK_L3;
generate_call_and_return_stmts(INDENT3);
r_output << CLOSE_BLOCK_L2;
} else {
r_output << c_in_statements.as_string();
r_output << INDENT2 "void** " C_LOCAL_PTRCALL_ARGS " = stackalloc void*["
<< argc_str << "] { " << c_args_var_content.as_string() << " };\n";
generate_call_and_return_stmts(INDENT2);
}
} else {
generate_call_and_return_stmts(INDENT2);
}
r_output << CLOSE_BLOCK_L1;
return OK;
}
Error BindingsGenerator::_save_file(const String &p_path, const StringBuilder &p_content) {
Ref<FileAccess> file = FileAccess::open(p_path, FileAccess::WRITE);
ERR_FAIL_COND_V_MSG(file.is_null(), ERR_FILE_CANT_WRITE, "Cannot open file: '" + p_path + "'.");
file->store_string(p_content.as_string());
return OK;
}
const BindingsGenerator::TypeInterface *BindingsGenerator::_get_type_or_null(const TypeReference &p_typeref) {
HashMap<StringName, TypeInterface>::ConstIterator builtin_type_match = builtin_types.find(p_typeref.cname);
if (builtin_type_match) {
return &builtin_type_match->value;
}
HashMap<StringName, TypeInterface>::ConstIterator obj_type_match = obj_types.find(p_typeref.cname);
if (obj_type_match) {
return &obj_type_match->value;
}
if (p_typeref.is_enum) {
HashMap<StringName, TypeInterface>::ConstIterator enum_match = enum_types.find(p_typeref.cname);
if (enum_match) {
return &enum_match->value;
}
// Enum not found. Most likely because none of its constants were bound, so it's empty. That's fine. Use int instead.
HashMap<StringName, TypeInterface>::ConstIterator int_match = builtin_types.find(name_cache.type_int);
ERR_FAIL_NULL_V(int_match, nullptr);
return &int_match->value;
}
return nullptr;
}
const String BindingsGenerator::_get_generic_type_parameters(const TypeInterface &p_itype, const List<TypeReference> &p_generic_type_parameters) {
if (p_generic_type_parameters.is_empty()) {
return "";
}
ERR_FAIL_COND_V_MSG(p_itype.type_parameter_count != p_generic_type_parameters.size(), "",
"Generic type parameter count mismatch for type '" + p_itype.name + "'." +
" Found " + itos(p_generic_type_parameters.size()) + ", but requires " +
itos(p_itype.type_parameter_count) + ".");
int i = 0;
String params = "<";
for (const TypeReference ¶m_type : p_generic_type_parameters) {
const TypeInterface *param_itype = _get_type_or_null(param_type);
ERR_FAIL_NULL_V(param_itype, "");
ERR_FAIL_COND_V_MSG(param_itype->is_singleton, "",
"Generic type parameter is a singleton: '" + param_itype->name + "'.");
if (p_itype.api_type == ClassDB::API_CORE) {
ERR_FAIL_COND_V_MSG(param_itype->api_type == ClassDB::API_EDITOR, "",
"Generic type parameter '" + param_itype->name + "' has type from the editor API." +
" Core API cannot have dependencies on the editor API.");
}
params += param_itype->cs_type;
if (i < p_generic_type_parameters.size() - 1) {
params += ", ";
}
i++;
}
params += ">";
return params;
}
StringName BindingsGenerator::_get_int_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
switch (p_meta) {
case GodotTypeInfo::METADATA_INT_IS_INT8:
return "sbyte";
break;
case GodotTypeInfo::METADATA_INT_IS_INT16:
return "short";
break;
case GodotTypeInfo::METADATA_INT_IS_INT32:
return "int";
break;
case GodotTypeInfo::METADATA_INT_IS_INT64:
return "long";
break;
case GodotTypeInfo::METADATA_INT_IS_UINT8:
return "byte";
break;
case GodotTypeInfo::METADATA_INT_IS_UINT16:
return "ushort";
break;
case GodotTypeInfo::METADATA_INT_IS_UINT32:
return "uint";
break;
case GodotTypeInfo::METADATA_INT_IS_UINT64:
return "ulong";
break;
default:
// Assume INT32
return "int";
}
}
StringName BindingsGenerator::_get_float_type_name_from_meta(GodotTypeInfo::Metadata p_meta) {
switch (p_meta) {
case GodotTypeInfo::METADATA_REAL_IS_FLOAT:
return "float";
break;
case GodotTypeInfo::METADATA_REAL_IS_DOUBLE:
return "double";
break;
default:
// Assume real_t (float or double depending of REAL_T_IS_DOUBLE)
#ifdef REAL_T_IS_DOUBLE
return "double";
#else
return "float";
#endif
}
}
bool BindingsGenerator::_arg_default_value_is_assignable_to_type(const Variant &p_val, const TypeInterface &p_arg_type) {
if (p_arg_type.name == name_cache.type_Variant) {
// Variant can take anything
return true;
}
switch (p_val.get_type()) {
case Variant::NIL:
return p_arg_type.is_object_type ||
name_cache.is_nullable_type(p_arg_type.name);
case Variant::BOOL:
return p_arg_type.name == name_cache.type_bool;
case Variant::INT:
return p_arg_type.name == name_cache.type_sbyte ||
p_arg_type.name == name_cache.type_short ||
p_arg_type.name == name_cache.type_int ||
p_arg_type.name == name_cache.type_byte ||
p_arg_type.name == name_cache.type_ushort ||
p_arg_type.name == name_cache.type_uint ||
p_arg_type.name == name_cache.type_long ||
p_arg_type.name == name_cache.type_ulong ||
p_arg_type.name == name_cache.type_float ||
p_arg_type.name == name_cache.type_double ||
p_arg_type.is_enum;
case Variant::FLOAT:
return p_arg_type.name == name_cache.type_float ||
p_arg_type.name == name_cache.type_double;
case Variant::STRING:
case Variant::STRING_NAME:
return p_arg_type.name == name_cache.type_String ||
p_arg_type.name == name_cache.type_StringName ||
p_arg_type.name == name_cache.type_NodePath;
case Variant::NODE_PATH:
return p_arg_type.name == name_cache.type_NodePath;
case Variant::TRANSFORM2D:
case Variant::TRANSFORM3D:
case Variant::BASIS:
case Variant::QUATERNION:
case Variant::PLANE:
case Variant::AABB:
case Variant::COLOR:
case Variant::VECTOR2:
case Variant::RECT2:
case Variant::VECTOR3:
case Variant::RID:
case Variant::PACKED_BYTE_ARRAY:
case Variant::PACKED_INT32_ARRAY:
case Variant::PACKED_INT64_ARRAY:
case Variant::PACKED_FLOAT32_ARRAY:
case Variant::PACKED_FLOAT64_ARRAY:
case Variant::PACKED_STRING_ARRAY:
case Variant::PACKED_VECTOR2_ARRAY:
case Variant::PACKED_VECTOR3_ARRAY:
case Variant::PACKED_COLOR_ARRAY:
case Variant::CALLABLE:
case Variant::SIGNAL:
return p_arg_type.name == Variant::get_type_name(p_val.get_type());
case Variant::ARRAY:
return p_arg_type.name == Variant::get_type_name(p_val.get_type()) || p_arg_type.cname == name_cache.type_Array_generic;
case Variant::DICTIONARY:
return p_arg_type.name == Variant::get_type_name(p_val.get_type()) || p_arg_type.cname == name_cache.type_Dictionary_generic;
case Variant::OBJECT:
return p_arg_type.is_object_type;
case Variant::VECTOR2I:
return p_arg_type.name == name_cache.type_Vector2 ||
p_arg_type.name == Variant::get_type_name(p_val.get_type());
case Variant::RECT2I:
return p_arg_type.name == name_cache.type_Rect2 ||
p_arg_type.name == Variant::get_type_name(p_val.get_type());
case Variant::VECTOR3I:
return p_arg_type.name == name_cache.type_Vector3 ||
p_arg_type.name == Variant::get_type_name(p_val.get_type());
default:
CRASH_NOW_MSG("Unexpected Variant type: " + itos(p_val.get_type()));
break;
}
return false;
}
bool BindingsGenerator::_populate_object_type_interfaces() {
obj_types.clear();
List<StringName> class_list;
ClassDB::get_class_list(&class_list);
class_list.sort_custom<StringName::AlphCompare>();
while (class_list.size()) {
StringName type_cname = class_list.front()->get();
ClassDB::APIType api_type = ClassDB::get_api_type(type_cname);
if (api_type == ClassDB::API_NONE) {
class_list.pop_front();
continue;
}
if (ignored_types.has(type_cname)) {
_log("Ignoring type '%s' because it's in the list of ignored types\n", String(type_cname).utf8().get_data());
class_list.pop_front();
continue;
}
if (!ClassDB::is_class_exposed(type_cname)) {
_log("Ignoring type '%s' because it's not exposed\n", String(type_cname).utf8().get_data());
class_list.pop_front();
continue;
}
if (!ClassDB::is_class_enabled(type_cname)) {
_log("Ignoring type '%s' because it's not enabled\n", String(type_cname).utf8().get_data());
class_list.pop_front();
continue;
}
ClassDB::ClassInfo *class_info = ClassDB::classes.getptr(type_cname);
TypeInterface itype = TypeInterface::create_object_type(type_cname, api_type);
itype.base_name = ClassDB::get_parent_class(type_cname);
itype.is_singleton = Engine::get_singleton()->has_singleton(itype.proxy_name);
itype.is_instantiable = class_info->creation_func && !itype.is_singleton;
itype.is_ref_counted = ClassDB::is_parent_class(type_cname, name_cache.type_RefCounted);
itype.memory_own = itype.is_ref_counted;
itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToGodotObject(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromGodotObject(%0)";
itype.c_out = "%5return ";
itype.c_out += C_METHOD_UNMANAGED_GET_MANAGED;
itype.c_out += itype.is_ref_counted ? "(%1.Reference);\n" : "(%1);\n";
itype.cs_type = itype.proxy_name;
if (itype.is_singleton) {
itype.cs_in_expr = "Object." CS_STATIC_METHOD_GETINSTANCE "(" CS_PROPERTY_SINGLETON ")";
} else {
itype.cs_in_expr = "Object." CS_STATIC_METHOD_GETINSTANCE "(%0)";
}
itype.cs_out = "%5return (%2)%0(%1);";
itype.c_arg_in = "(void*)%s";
itype.c_type = "IntPtr";
itype.c_type_in = itype.c_type;
itype.c_type_out = "Object";
// Populate properties
List<PropertyInfo> property_list;
ClassDB::get_property_list(type_cname, &property_list, true);
HashMap<StringName, StringName> accessor_methods;
for (const PropertyInfo &property : property_list) {
if (property.usage & PROPERTY_USAGE_GROUP || property.usage & PROPERTY_USAGE_SUBGROUP || property.usage & PROPERTY_USAGE_CATEGORY || (property.type == Variant::NIL && property.usage & PROPERTY_USAGE_ARRAY)) {
continue;
}
if (property.name.find("/") >= 0) {
// Ignore properties with '/' (slash) in the name. These are only meant for use in the inspector.
continue;
}
PropertyInterface iprop;
iprop.cname = property.name;
iprop.setter = ClassDB::get_property_setter(type_cname, iprop.cname);
iprop.getter = ClassDB::get_property_getter(type_cname, iprop.cname);
if (iprop.setter != StringName()) {
accessor_methods[iprop.setter] = iprop.cname;
}
if (iprop.getter != StringName()) {
accessor_methods[iprop.getter] = iprop.cname;
}
bool valid = false;
iprop.index = ClassDB::get_property_index(type_cname, iprop.cname, &valid);
ERR_FAIL_COND_V_MSG(!valid, false, "Invalid property: '" + itype.name + "." + String(iprop.cname) + "'.");
iprop.proxy_name = escape_csharp_keyword(snake_to_pascal_case(iprop.cname));
// Prevent the property and its enclosing type from sharing the same name
if (iprop.proxy_name == itype.proxy_name) {
_log("Name of property '%s' is ambiguous with the name of its enclosing class '%s'. Renaming property to '%s_'\n",
iprop.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), iprop.proxy_name.utf8().get_data());
iprop.proxy_name += "_";
}
iprop.prop_doc = nullptr;
for (int i = 0; i < itype.class_doc->properties.size(); i++) {
const DocData::PropertyDoc &prop_doc = itype.class_doc->properties[i];
if (prop_doc.name == iprop.cname) {
iprop.prop_doc = &prop_doc;
break;
}
}
itype.properties.push_back(iprop);
}
// Populate methods
List<MethodInfo> virtual_method_list;
ClassDB::get_virtual_methods(type_cname, &virtual_method_list, true);
List<MethodInfo> method_list;
ClassDB::get_method_list(type_cname, &method_list, true);
method_list.sort();
for (const MethodInfo &method_info : method_list) {
int argc = method_info.arguments.size();
if (method_info.name.is_empty()) {
continue;
}
String cname = method_info.name;
if (blacklisted_methods.find(itype.cname) && blacklisted_methods[itype.cname].find(cname)) {
continue;
}
MethodInterface imethod;
imethod.name = method_info.name;
imethod.cname = cname;
if (method_info.flags & METHOD_FLAG_STATIC) {
imethod.is_static = true;
}
if (method_info.flags & METHOD_FLAG_VIRTUAL) {
imethod.is_virtual = true;
itype.has_virtual_methods = true;
}
PropertyInfo return_info = method_info.return_val;
MethodBind *m = imethod.is_virtual ? nullptr : ClassDB::get_method(type_cname, method_info.name);
imethod.is_vararg = m && m->is_vararg();
if (!m && !imethod.is_virtual) {
ERR_FAIL_COND_V_MSG(!virtual_method_list.find(method_info), false,
"Missing MethodBind for non-virtual method: '" + itype.name + "." + imethod.name + "'.");
// A virtual method without the virtual flag. This is a special case.
// There is no method bind, so let's fallback to Godot's object.Call(string, params)
imethod.requires_object_call = true;
// The method Object.free is registered as a virtual method, but without the virtual flag.
// This is because this method is not supposed to be overridden, but called.
// We assume the return type is void.
imethod.return_type.cname = name_cache.type_void;
// Actually, more methods like this may be added in the future, which could return
// something different. Let's put this check to notify us if that ever happens.
if (itype.cname != name_cache.type_Object || imethod.name != "free") {
WARN_PRINT("Notification: New unexpected virtual non-overridable method found."
" We only expected Object.free, but found '" +
itype.name + "." + imethod.name + "'.");
}
} else if (return_info.type == Variant::INT && return_info.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
imethod.return_type.cname = return_info.class_name;
imethod.return_type.is_enum = true;
} else if (return_info.class_name != StringName()) {
imethod.return_type.cname = return_info.class_name;
bool bad_reference_hint = !imethod.is_virtual && return_info.hint != PROPERTY_HINT_RESOURCE_TYPE &&
ClassDB::is_parent_class(return_info.class_name, name_cache.type_RefCounted);
ERR_FAIL_COND_V_MSG(bad_reference_hint, false,
String() + "Return type is reference but hint is not '" _STR(PROPERTY_HINT_RESOURCE_TYPE) "'." +
" Are you returning a reference type by pointer? Method: '" + itype.name + "." + imethod.name + "'.");
} else if (return_info.type == Variant::ARRAY && return_info.hint == PROPERTY_HINT_ARRAY_TYPE) {
imethod.return_type.cname = Variant::get_type_name(return_info.type) + "_@generic";
imethod.return_type.generic_type_parameters.push_back(TypeReference(return_info.hint_string));
} else if (return_info.hint == PROPERTY_HINT_RESOURCE_TYPE) {
imethod.return_type.cname = return_info.hint_string;
} else if (return_info.type == Variant::NIL && return_info.usage & PROPERTY_USAGE_NIL_IS_VARIANT) {
imethod.return_type.cname = name_cache.type_Variant;
} else if (return_info.type == Variant::NIL) {
imethod.return_type.cname = name_cache.type_void;
} else {
if (return_info.type == Variant::INT) {
imethod.return_type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE);
} else if (return_info.type == Variant::FLOAT) {
imethod.return_type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(-1) : GodotTypeInfo::METADATA_NONE);
} else {
imethod.return_type.cname = Variant::get_type_name(return_info.type);
}
}
for (int i = 0; i < argc; i++) {
PropertyInfo arginfo = method_info.arguments[i];
String orig_arg_name = arginfo.name;
ArgumentInterface iarg;
iarg.name = orig_arg_name;
if (arginfo.type == Variant::INT && arginfo.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
iarg.type.cname = arginfo.class_name;
iarg.type.is_enum = true;
} else if (arginfo.class_name != StringName()) {
iarg.type.cname = arginfo.class_name;
} else if (arginfo.type == Variant::ARRAY && arginfo.hint == PROPERTY_HINT_ARRAY_TYPE) {
iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
iarg.type.generic_type_parameters.push_back(TypeReference(arginfo.hint_string));
} else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
iarg.type.cname = arginfo.hint_string;
} else if (arginfo.type == Variant::NIL) {
iarg.type.cname = name_cache.type_Variant;
} else {
if (arginfo.type == Variant::INT) {
iarg.type.cname = _get_int_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE);
} else if (arginfo.type == Variant::FLOAT) {
iarg.type.cname = _get_float_type_name_from_meta(m ? m->get_argument_meta(i) : GodotTypeInfo::METADATA_NONE);
} else {
iarg.type.cname = Variant::get_type_name(arginfo.type);
}
}
iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
if (m && m->has_default_argument(i)) {
bool defval_ok = _arg_default_value_from_variant(m->get_default_argument(i), iarg);
ERR_FAIL_COND_V_MSG(!defval_ok, false,
"Cannot determine default value for argument '" + orig_arg_name + "' of method '" + itype.name + "." + imethod.name + "'.");
}
imethod.add_argument(iarg);
}
if (imethod.is_vararg) {
ArgumentInterface ivararg;
ivararg.type.cname = name_cache.type_VarArg;
ivararg.name = "@args";
imethod.add_argument(ivararg);
}
imethod.proxy_name = escape_csharp_keyword(snake_to_pascal_case(imethod.name));
// Prevent the method and its enclosing type from sharing the same name
if (imethod.proxy_name == itype.proxy_name) {
_log("Name of method '%s' is ambiguous with the name of its enclosing class '%s'. Renaming method to '%s_'\n",
imethod.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), imethod.proxy_name.utf8().get_data());
imethod.proxy_name += "_";
}
HashMap<StringName, StringName>::Iterator accessor = accessor_methods.find(imethod.cname);
if (accessor) {
const PropertyInterface *accessor_property = itype.find_property_by_name(accessor->value);
// We only deprecate an accessor method if it's in the same class as the property. It's easier this way, but also
// we don't know if an accessor method in a different class could have other purposes, so better leave those untouched.
imethod.is_deprecated = true;
imethod.deprecation_message = imethod.proxy_name + " is deprecated. Use the " + accessor_property->proxy_name + " property instead.";
}
if (itype.class_doc) {
for (int i = 0; i < itype.class_doc->methods.size(); i++) {
if (itype.class_doc->methods[i].name == imethod.name) {
imethod.method_doc = &itype.class_doc->methods[i];
break;
}
}
}
ERR_FAIL_COND_V_MSG(itype.find_property_by_name(imethod.cname), false,
"Method name conflicts with property: '" + itype.name + "." + imethod.name + "'.");
// Methods starting with an underscore are ignored unless they're used as a property setter or getter
if (!imethod.is_virtual && imethod.name[0] == '_') {
for (const PropertyInterface &iprop : itype.properties) {
if (iprop.setter == imethod.name || iprop.getter == imethod.name) {
imethod.is_internal = true;
itype.methods.push_back(imethod);
break;
}
}
} else {
itype.methods.push_back(imethod);
}
}
// Populate signals
const HashMap<StringName, MethodInfo> &signal_map = class_info->signal_map;
for (const KeyValue<StringName, MethodInfo> &E : signal_map) {
SignalInterface isignal;
const MethodInfo &method_info = E.value;
isignal.name = method_info.name;
isignal.cname = method_info.name;
int argc = method_info.arguments.size();
for (int i = 0; i < argc; i++) {
PropertyInfo arginfo = method_info.arguments[i];
String orig_arg_name = arginfo.name;
ArgumentInterface iarg;
iarg.name = orig_arg_name;
if (arginfo.type == Variant::INT && arginfo.usage & (PROPERTY_USAGE_CLASS_IS_ENUM | PROPERTY_USAGE_CLASS_IS_BITFIELD)) {
iarg.type.cname = arginfo.class_name;
iarg.type.is_enum = true;
} else if (arginfo.class_name != StringName()) {
iarg.type.cname = arginfo.class_name;
} else if (arginfo.type == Variant::ARRAY && arginfo.hint == PROPERTY_HINT_ARRAY_TYPE) {
iarg.type.cname = Variant::get_type_name(arginfo.type) + "_@generic";
iarg.type.generic_type_parameters.push_back(TypeReference(arginfo.hint_string));
} else if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) {
iarg.type.cname = arginfo.hint_string;
} else if (arginfo.type == Variant::NIL) {
iarg.type.cname = name_cache.type_Variant;
} else {
if (arginfo.type == Variant::INT) {
iarg.type.cname = _get_int_type_name_from_meta(GodotTypeInfo::METADATA_NONE);
} else if (arginfo.type == Variant::FLOAT) {
iarg.type.cname = _get_float_type_name_from_meta(GodotTypeInfo::METADATA_NONE);
} else {
iarg.type.cname = Variant::get_type_name(arginfo.type);
}
}
iarg.name = escape_csharp_keyword(snake_to_camel_case(iarg.name));
isignal.add_argument(iarg);
}
isignal.proxy_name = escape_csharp_keyword(snake_to_pascal_case(isignal.name));
// Prevent the signal and its enclosing type from sharing the same name
if (isignal.proxy_name == itype.proxy_name) {
_log("Name of signal '%s' is ambiguous with the name of its enclosing class '%s'. Renaming signal to '%s_'\n",
isignal.proxy_name.utf8().get_data(), itype.proxy_name.utf8().get_data(), isignal.proxy_name.utf8().get_data());
isignal.proxy_name += "_";
}
if (itype.find_property_by_proxy_name(isignal.proxy_name) || itype.find_method_by_proxy_name(isignal.proxy_name)) {
// ClassDB allows signal names that conflict with method or property names.
// While registering a signal with a conflicting name is considered wrong,
// it may still happen and it may take some time until someone fixes the name.
// We can't allow the bindings to be in a broken state while we wait for a fix;
// that's why we must handle this possibility by renaming the signal.
isignal.proxy_name += "Signal";
}
if (itype.class_doc) {
for (int i = 0; i < itype.class_doc->signals.size(); i++) {
const DocData::MethodDoc &signal_doc = itype.class_doc->signals[i];
if (signal_doc.name == isignal.name) {
isignal.method_doc = &signal_doc;
break;
}
}
}
itype.signals_.push_back(isignal);
}
// Populate enums and constants
List<String> constants;
ClassDB::get_integer_constant_list(type_cname, &constants, true);
const HashMap<StringName, ClassDB::ClassInfo::EnumInfo> &enum_map = class_info->enum_map;
for (const KeyValue<StringName, ClassDB::ClassInfo::EnumInfo> &E : enum_map) {
StringName enum_proxy_cname = E.key;
String enum_proxy_name = enum_proxy_cname.operator String();
if (itype.find_property_by_proxy_name(enum_proxy_cname)) {
// We have several conflicts between enums and PascalCase properties,
// so we append 'Enum' to the enum name in those cases.
enum_proxy_name += "Enum";
enum_proxy_cname = StringName(enum_proxy_name);
}
EnumInterface ienum(enum_proxy_cname);
ienum.is_flags = E.value.is_bitfield;
const List<StringName> &enum_constants = E.value.constants;
for (const StringName &constant_cname : enum_constants) {
String constant_name = constant_cname.operator String();
int64_t *value = class_info->constant_map.getptr(constant_cname);
ERR_FAIL_NULL_V(value, false);
constants.erase(constant_name);
ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
iconstant.const_doc = nullptr;
for (int i = 0; i < itype.class_doc->constants.size(); i++) {
const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
if (const_doc.name == iconstant.name) {
iconstant.const_doc = &const_doc;
break;
}
}
ienum.constants.push_back(iconstant);
}
int prefix_length = _determine_enum_prefix(ienum);
_apply_prefix_to_enum_constants(ienum, prefix_length);
itype.enums.push_back(ienum);
TypeInterface enum_itype;
enum_itype.is_enum = true;
enum_itype.name = itype.name + "." + String(E.key);
enum_itype.cname = StringName(enum_itype.name);
enum_itype.proxy_name = itype.proxy_name + "." + enum_proxy_name;
TypeInterface::postsetup_enum_type(enum_itype);
enum_itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToInt32(%0)";
enum_itype.cs_managed_to_variant = "VariantUtils.CreateFromInt((int)%0)";
enum_types.insert(enum_itype.cname, enum_itype);
}
for (const String &constant_name : constants) {
int64_t *value = class_info->constant_map.getptr(StringName(constant_name));
ERR_FAIL_NULL_V(value, false);
ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), *value);
iconstant.const_doc = nullptr;
for (int i = 0; i < itype.class_doc->constants.size(); i++) {
const DocData::ConstantDoc &const_doc = itype.class_doc->constants[i];
if (const_doc.name == iconstant.name) {
iconstant.const_doc = &const_doc;
break;
}
}
itype.constants.push_back(iconstant);
}
obj_types.insert(itype.cname, itype);
class_list.pop_front();
}
return true;
}
bool BindingsGenerator::_arg_default_value_from_variant(const Variant &p_val, ArgumentInterface &r_iarg) {
r_iarg.def_param_value = p_val;
r_iarg.default_argument = p_val.operator String();
switch (p_val.get_type()) {
case Variant::NIL:
// Either Object type or Variant
r_iarg.default_argument = "default";
break;
// Atomic types
case Variant::BOOL:
r_iarg.default_argument = bool(p_val) ? "true" : "false";
break;
case Variant::INT:
if (r_iarg.type.cname != name_cache.type_int) {
r_iarg.default_argument = "(%s)" + r_iarg.default_argument;
}
break;
case Variant::FLOAT:
if (r_iarg.type.cname == name_cache.type_float) {
r_iarg.default_argument += "f";
}
break;
case Variant::STRING:
case Variant::STRING_NAME:
case Variant::NODE_PATH:
if (r_iarg.type.cname == name_cache.type_StringName || r_iarg.type.cname == name_cache.type_NodePath) {
if (r_iarg.default_argument.length() > 0) {
r_iarg.default_argument = "(%s)\"" + r_iarg.default_argument + "\"";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
} else {
// No need for a special `in` statement to change `null` to `""`. Marshaling takes care of this already.
r_iarg.default_argument = "null";
}
} else {
CRASH_COND(r_iarg.type.cname != name_cache.type_String);
r_iarg.default_argument = "\"" + r_iarg.default_argument + "\"";
}
break;
case Variant::PLANE: {
Plane plane = p_val.operator Plane();
r_iarg.default_argument = "new Plane(new Vector3" + plane.normal.operator String() + ", " + rtos(plane.d) + ")";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::AABB: {
AABB aabb = p_val.operator ::AABB();
r_iarg.default_argument = "new AABB(new Vector3" + aabb.position.operator String() + ", new Vector3" + aabb.size.operator String() + ")";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::RECT2: {
Rect2 rect = p_val.operator Rect2();
r_iarg.default_argument = "new Rect2(new Vector2" + rect.position.operator String() + ", new Vector2" + rect.size.operator String() + ")";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::RECT2I: {
Rect2i rect = p_val.operator Rect2i();
r_iarg.default_argument = "new Rect2i(new Vector2i" + rect.position.operator String() + ", new Vector2i" + rect.size.operator String() + ")";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::COLOR:
case Variant::VECTOR2:
case Variant::VECTOR2I:
case Variant::VECTOR3:
case Variant::VECTOR3I:
r_iarg.default_argument = "new %s" + r_iarg.default_argument;
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
break;
case Variant::VECTOR4:
case Variant::VECTOR4I:
r_iarg.default_argument = "new %s" + r_iarg.default_argument;
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
break;
case Variant::OBJECT:
ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
"Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
r_iarg.default_argument = "null";
break;
case Variant::DICTIONARY:
ERR_FAIL_COND_V_MSG(!p_val.operator Dictionary().is_empty(), false,
"Default value of type 'Dictionary' must be an empty dictionary.");
// The [cs_in] expression already interprets null values as empty dictionaries.
r_iarg.default_argument = "null";
r_iarg.def_param_mode = ArgumentInterface::CONSTANT;
break;
case Variant::RID:
ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_RID, false,
"Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_RID) + "'.");
ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
"Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
r_iarg.default_argument = "default";
break;
case Variant::ARRAY:
ERR_FAIL_COND_V_MSG(!p_val.operator Array().is_empty(), false,
"Default value of type 'Array' must be an empty array.");
// The [cs_in] expression already interprets null values as empty arrays.
r_iarg.default_argument = "null";
r_iarg.def_param_mode = ArgumentInterface::CONSTANT;
break;
case Variant::PACKED_BYTE_ARRAY:
case Variant::PACKED_INT32_ARRAY:
case Variant::PACKED_INT64_ARRAY:
case Variant::PACKED_FLOAT32_ARRAY:
case Variant::PACKED_FLOAT64_ARRAY:
case Variant::PACKED_STRING_ARRAY:
case Variant::PACKED_VECTOR2_ARRAY:
case Variant::PACKED_VECTOR3_ARRAY:
case Variant::PACKED_COLOR_ARRAY:
r_iarg.default_argument = "Array.Empty<%s>()";
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_REF;
break;
case Variant::TRANSFORM2D: {
Transform2D transform = p_val.operator Transform2D();
if (transform == Transform2D()) {
r_iarg.default_argument = "Transform2D.Identity";
} else {
r_iarg.default_argument = "new Transform2D(new Vector2" + transform.columns[0].operator String() + ", new Vector2" + transform.columns[1].operator String() + ", new Vector2" + transform.columns[2].operator String() + ")";
}
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::TRANSFORM3D: {
Transform3D transform = p_val.operator Transform3D();
if (transform == Transform3D()) {
r_iarg.default_argument = "Transform3D.Identity";
} else {
Basis basis = transform.basis;
r_iarg.default_argument = "new Transform3D(new Vector3" + basis.get_column(0).operator String() + ", new Vector3" + basis.get_column(1).operator String() + ", new Vector3" + basis.get_column(2).operator String() + ", new Vector3" + transform.origin.operator String() + ")";
}
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::PROJECTION: {
Projection transform = p_val.operator Projection();
if (transform == Projection()) {
r_iarg.default_argument = "Projection.Identity";
} else {
r_iarg.default_argument = "new Projection(new Vector4" + transform.matrix[0].operator String() + ", new Vector4" + transform.matrix[1].operator String() + ", new Vector4" + transform.matrix[2].operator String() + ", new Vector4" + transform.matrix[3].operator String() + ")";
}
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::BASIS: {
Basis basis = p_val.operator Basis();
if (basis == Basis()) {
r_iarg.default_argument = "Basis.Identity";
} else {
r_iarg.default_argument = "new Basis(new Vector3" + basis.get_column(0).operator String() + ", new Vector3" + basis.get_column(1).operator String() + ", new Vector3" + basis.get_column(2).operator String() + ")";
}
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::QUATERNION: {
Quaternion quaternion = p_val.operator Quaternion();
if (quaternion == Quaternion()) {
r_iarg.default_argument = "Quaternion.Identity";
} else {
r_iarg.default_argument = "new Quaternion" + quaternion.operator String();
}
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
} break;
case Variant::CALLABLE:
ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_Callable, false,
"Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_Callable) + "'.");
ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
"Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
r_iarg.default_argument = "default";
break;
case Variant::SIGNAL:
ERR_FAIL_COND_V_MSG(r_iarg.type.cname != name_cache.type_Signal, false,
"Parameter of type '" + String(r_iarg.type.cname) + "' cannot have a default value of type '" + String(name_cache.type_Signal) + "'.");
ERR_FAIL_COND_V_MSG(!p_val.is_zero(), false,
"Parameter of type '" + String(r_iarg.type.cname) + "' can only have null/zero as the default value.");
r_iarg.default_argument = "default";
break;
default:
ERR_FAIL_V_MSG(false, "Unexpected Variant type: " + itos(p_val.get_type()));
break;
}
if (r_iarg.def_param_mode == ArgumentInterface::CONSTANT && r_iarg.type.cname == name_cache.type_Variant && r_iarg.default_argument != "default") {
r_iarg.def_param_mode = ArgumentInterface::NULLABLE_VAL;
}
return true;
}
void BindingsGenerator::_populate_builtin_type_interfaces() {
builtin_types.clear();
TypeInterface itype;
#define INSERT_STRUCT_TYPE(m_type) \
{ \
itype = TypeInterface::create_value_type(String(#m_type)); \
itype.c_type_in = #m_type "*"; \
itype.c_type_out = itype.cs_type; \
itype.cs_in_expr = "&%0"; \
itype.cs_in_expr_is_unsafe = true; \
itype.cs_variant_to_managed = "VariantUtils.ConvertTo%2(%0)"; \
itype.cs_managed_to_variant = "VariantUtils.CreateFrom%2(%0)"; \
builtin_types.insert(itype.cname, itype); \
}
INSERT_STRUCT_TYPE(Vector2)
INSERT_STRUCT_TYPE(Vector2i)
INSERT_STRUCT_TYPE(Rect2)
INSERT_STRUCT_TYPE(Rect2i)
INSERT_STRUCT_TYPE(Transform2D)
INSERT_STRUCT_TYPE(Vector3)
INSERT_STRUCT_TYPE(Vector3i)
INSERT_STRUCT_TYPE(Basis)
INSERT_STRUCT_TYPE(Quaternion)
INSERT_STRUCT_TYPE(Transform3D)
INSERT_STRUCT_TYPE(AABB)
INSERT_STRUCT_TYPE(Color)
INSERT_STRUCT_TYPE(Plane)
INSERT_STRUCT_TYPE(Vector4)
INSERT_STRUCT_TYPE(Vector4i)
INSERT_STRUCT_TYPE(Projection)
#undef INSERT_STRUCT_TYPE
// bool
itype = TypeInterface::create_value_type(String("bool"));
itype.cs_in_expr = "%0.ToGodotBool()";
itype.cs_out = "%5return %0(%1).ToBool();";
itype.c_type = "godot_bool";
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.c_type;
itype.c_arg_in = "&%s";
itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromBool(%1);\n";
itype.cs_variant_to_managed = "VariantUtils.ConvertToBool(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromBool(%0)";
builtin_types.insert(itype.cname, itype);
// Integer types
{
// C interface for 'uint32_t' is the same as that of enums. Remember to apply
// any of the changes done here to 'TypeInterface::postsetup_enum_type' as well.
#define INSERT_INT_TYPE(m_name, m_int_struct_name) \
{ \
itype = TypeInterface::create_value_type(String(m_name)); \
if (itype.name != "long" && itype.name != "ulong") { \
itype.c_in = "%5%0 %1_in = %1;\n"; \
itype.c_out = "%5return (%0)%1;\n"; \
itype.c_type = "long"; \
itype.c_arg_in = "&%s_in"; \
} else { \
itype.c_arg_in = "&%s"; \
} \
itype.c_type_in = itype.name; \
itype.c_type_out = itype.name; \
itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromInt(%1);\n"; \
itype.cs_variant_to_managed = "VariantUtils.ConvertTo" m_int_struct_name "(%0)"; \
itype.cs_managed_to_variant = "VariantUtils.CreateFromInt(%0)"; \
builtin_types.insert(itype.cname, itype); \
}
// The expected type for all integers in ptrcall is 'int64_t', so that's what we use for 'c_type'
INSERT_INT_TYPE("sbyte", "Int8");
INSERT_INT_TYPE("short", "Int16");
INSERT_INT_TYPE("int", "Int32");
INSERT_INT_TYPE("long", "Int64");
INSERT_INT_TYPE("byte", "UInt8");
INSERT_INT_TYPE("ushort", "UInt16");
INSERT_INT_TYPE("uint", "UInt32");
INSERT_INT_TYPE("ulong", "UInt64");
#undef INSERT_INT_TYPE
}
// Floating point types
{
// float
itype = TypeInterface();
itype.name = "float";
itype.cname = itype.name;
itype.proxy_name = "float";
itype.cs_type = itype.proxy_name;
{
// The expected type for 'float' in ptrcall is 'double'
itype.c_in = "%5%0 %1_in = %1;\n";
itype.c_out = "%5return (%0)%1;\n";
itype.c_type = "double";
itype.c_arg_in = "&%s_in";
}
itype.c_type_in = itype.proxy_name;
itype.c_type_out = itype.proxy_name;
itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromFloat(%1);\n";
itype.cs_variant_to_managed = "VariantUtils.ConvertToFloat32(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromFloat(%0)";
builtin_types.insert(itype.cname, itype);
// double
itype = TypeInterface();
itype.name = "double";
itype.cname = itype.name;
itype.proxy_name = "double";
itype.cs_type = itype.proxy_name;
itype.c_type = "double";
itype.c_arg_in = "&%s";
itype.c_type_in = itype.proxy_name;
itype.c_type_out = itype.proxy_name;
itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromFloat(%1);\n";
itype.cs_variant_to_managed = "VariantUtils.ConvertToFloat64(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromFloat(%0)";
builtin_types.insert(itype.cname, itype);
}
// String
itype = TypeInterface();
itype.name = "String";
itype.cname = itype.name;
itype.proxy_name = "string";
itype.cs_type = itype.proxy_name;
itype.c_in = "%5using %0 %1_in = " C_METHOD_MONOSTR_TO_GODOT "(%1);\n";
itype.c_out = "%5return " C_METHOD_MONOSTR_FROM_GODOT "(%1);\n";
itype.c_arg_in = "&%s_in";
itype.c_type = "godot_string";
itype.c_type_in = itype.cs_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = true;
itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromString(%1);\n";
itype.cs_variant_to_managed = "VariantUtils.ConvertToStringObject(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromString(%0)";
builtin_types.insert(itype.cname, itype);
// StringName
itype = TypeInterface();
itype.name = "StringName";
itype.cname = itype.name;
itype.proxy_name = "StringName";
itype.cs_type = itype.proxy_name;
itype.cs_in_expr = "(%1)(%0?.NativeValue ?? default)";
// Cannot pass null StringName to ptrcall
itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
itype.c_arg_in = "&%s";
itype.c_type = "godot_string_name";
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.cs_type;
itype.c_in_vararg = "%5using godot_variant %1_in = VariantUtils.CreateFromStringName(%1);\n";
itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
itype.c_ret_needs_default_initialization = true;
itype.cs_variant_to_managed = "VariantUtils.ConvertToStringNameObject(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromStringName(%0)";
builtin_types.insert(itype.cname, itype);
// NodePath
itype = TypeInterface();
itype.name = "NodePath";
itype.cname = itype.name;
itype.proxy_name = "NodePath";
itype.cs_type = itype.proxy_name;
itype.cs_in_expr = "(%1)(%0?.NativeValue ?? default)";
// Cannot pass null NodePath to ptrcall
itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
itype.c_arg_in = "&%s";
itype.c_type = "godot_node_path";
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
itype.c_ret_needs_default_initialization = true;
itype.cs_variant_to_managed = "VariantUtils.ConvertToNodePathObject(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromNodePath(%0)";
builtin_types.insert(itype.cname, itype);
// RID
itype = TypeInterface();
itype.name = "RID";
itype.cname = itype.name;
itype.proxy_name = "RID";
itype.cs_type = itype.proxy_name;
itype.c_arg_in = "&%s";
itype.c_type = itype.cs_type;
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.c_type;
itype.cs_variant_to_managed = "VariantUtils.ConvertToRID(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromRID(%0)";
builtin_types.insert(itype.cname, itype);
// Variant
itype = TypeInterface();
itype.name = "Variant";
itype.cname = itype.name;
itype.proxy_name = "Variant";
itype.cs_type = itype.proxy_name;
itype.c_in = "%5%0 %1_in = (%0)%1.NativeVar;\n";
itype.c_out = "%5return Variant.CreateTakingOwnershipOfDisposableValue(%1);\n";
itype.c_arg_in = "&%s_in";
itype.c_type = "godot_variant";
itype.c_type_in = itype.cs_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
itype.c_ret_needs_default_initialization = true;
itype.cs_variant_to_managed = "Variant.CreateCopyingBorrowed(%0)";
itype.cs_managed_to_variant = "%0.CopyNativeVariant()";
builtin_types.insert(itype.cname, itype);
// Callable
itype = TypeInterface::create_value_type(String("Callable"));
itype.cs_in_expr = "%0";
itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_CALLABLE "(in %1);\n";
itype.c_out = "%5return " C_METHOD_MANAGED_FROM_CALLABLE "(in %1);\n";
itype.c_arg_in = "&%s_in";
itype.c_type = "godot_callable";
itype.c_type_in = "in " + itype.cs_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = true;
itype.cs_variant_to_managed = "VariantUtils.ConvertToCallableManaged(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromCallable(%0)";
builtin_types.insert(itype.cname, itype);
// Signal
itype = TypeInterface();
itype.name = "Signal";
itype.cname = itype.name;
itype.proxy_name = "SignalInfo";
itype.cs_type = itype.proxy_name;
itype.cs_in_expr = "%0";
itype.c_in = "%5using %0 %1_in = " C_METHOD_MANAGED_TO_SIGNAL "(in %1);\n";
itype.c_out = "%5return " C_METHOD_MANAGED_FROM_SIGNAL "(&%1);\n";
itype.c_arg_in = "&%s_in";
itype.c_type = "godot_signal";
itype.c_type_in = "in " + itype.cs_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = true;
itype.cs_variant_to_managed = "VariantUtils.ConvertToSignalInfo(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromSignalInfo(%0)";
builtin_types.insert(itype.cname, itype);
// VarArg (fictitious type to represent variable arguments)
itype = TypeInterface();
itype.name = "VarArg";
itype.cname = itype.name;
itype.proxy_name = "Variant[]";
itype.cs_type = "params Variant[]";
itype.cs_in_expr = "%0 ?? Array.Empty<Variant>()";
// c_type, c_in and c_arg_in are hard-coded in the generator.
// c_out and c_type_out are not applicable to VarArg.
itype.c_arg_in = "&%s_in";
itype.c_type_in = "Variant[]";
builtin_types.insert(itype.cname, itype);
#define INSERT_ARRAY_FULL(m_name, m_type, m_managed_type, m_proxy_t) \
{ \
itype = TypeInterface(); \
itype.name = #m_name; \
itype.cname = itype.name; \
itype.proxy_name = #m_proxy_t "[]"; \
itype.cs_type = itype.proxy_name; \
itype.c_in = "%5using %0 %1_in = " C_METHOD_MONOARRAY_TO(m_type) "(%1);\n"; \
itype.c_out = "%5return " C_METHOD_MONOARRAY_FROM(m_type) "(%1);\n"; \
itype.c_arg_in = "&%s_in"; \
itype.c_type = #m_managed_type; \
itype.c_type_in = itype.proxy_name; \
itype.c_type_out = itype.proxy_name; \
itype.c_type_is_disposable_struct = true; \
itype.cs_variant_to_managed = "VariantUtils.ConvertAs%2ToSystemArray(%0)"; \
itype.cs_managed_to_variant = "VariantUtils.CreateFrom%2(%0)"; \
builtin_types.insert(itype.name, itype); \
}
#define INSERT_ARRAY(m_type, m_managed_type, m_proxy_t) INSERT_ARRAY_FULL(m_type, m_type, m_managed_type, m_proxy_t)
INSERT_ARRAY(PackedInt32Array, godot_packed_int32_array, int);
INSERT_ARRAY(PackedInt64Array, godot_packed_int64_array, long);
INSERT_ARRAY_FULL(PackedByteArray, PackedByteArray, godot_packed_byte_array, byte);
INSERT_ARRAY(PackedFloat32Array, godot_packed_float32_array, float);
INSERT_ARRAY(PackedFloat64Array, godot_packed_float64_array, double);
INSERT_ARRAY(PackedStringArray, godot_packed_string_array, string);
INSERT_ARRAY(PackedColorArray, godot_packed_color_array, Color);
INSERT_ARRAY(PackedVector2Array, godot_packed_vector2_array, Vector2);
INSERT_ARRAY(PackedVector3Array, godot_packed_vector3_array, Vector3);
#undef INSERT_ARRAY
// Array
itype = TypeInterface();
itype.name = "Array";
itype.cname = itype.name;
itype.proxy_name = itype.name;
itype.type_parameter_count = 1;
itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
itype.cs_in_expr = "(%1)(%0 ?? new()).NativeValue";
itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
itype.c_arg_in = "&%s";
itype.c_type = "godot_array";
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
itype.c_ret_needs_default_initialization = true;
itype.cs_variant_to_managed = "VariantUtils.ConvertToArrayObject(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromArray(%0)";
builtin_types.insert(itype.cname, itype);
// Array_@generic
// Re-use Array's itype
itype.name = "Array_@generic";
itype.cname = itype.name;
itype.cs_out = "%5return new %2(%0(%1));";
builtin_types.insert(itype.cname, itype);
// Dictionary
itype = TypeInterface();
itype.name = "Dictionary";
itype.cname = itype.name;
itype.proxy_name = itype.name;
itype.type_parameter_count = 2;
itype.cs_type = BINDINGS_NAMESPACE_COLLECTIONS "." + itype.proxy_name;
itype.cs_in_expr = "(%1)(%0 ?? new()).NativeValue";
itype.c_out = "%5return %0.CreateTakingOwnershipOfDisposableValue(%1);\n";
itype.c_arg_in = "&%s";
itype.c_type = "godot_dictionary";
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.cs_type;
itype.c_type_is_disposable_struct = false; // [c_out] takes ownership
itype.c_ret_needs_default_initialization = true;
itype.cs_variant_to_managed = "VariantUtils.ConvertToDictionaryObject(%0)";
itype.cs_managed_to_variant = "VariantUtils.CreateFromDictionary(%0)";
builtin_types.insert(itype.cname, itype);
// Dictionary_@generic
// Re-use Dictionary's itype
itype.name = "Dictionary_@generic";
itype.cname = itype.name;
itype.cs_out = "%5return new %2(%0(%1));";
builtin_types.insert(itype.cname, itype);
// void (fictitious type to represent the return type of methods that do not return anything)
itype = TypeInterface();
itype.name = "void";
itype.cname = itype.name;
itype.proxy_name = itype.name;
itype.cs_type = itype.proxy_name;
itype.c_type = itype.proxy_name;
itype.c_type_in = itype.c_type;
itype.c_type_out = itype.c_type;
builtin_types.insert(itype.cname, itype);
}
void BindingsGenerator::_populate_global_constants() {
int global_constants_count = CoreConstants::get_global_constant_count();
if (global_constants_count > 0) {
HashMap<String, DocData::ClassDoc>::Iterator match = EditorHelp::get_doc_data()->class_list.find("@GlobalScope");
CRASH_COND_MSG(!match, "Could not find '@GlobalScope' in DocData.");
const DocData::ClassDoc &global_scope_doc = match->value;
for (int i = 0; i < global_constants_count; i++) {
String constant_name = CoreConstants::get_global_constant_name(i);
const DocData::ConstantDoc *const_doc = nullptr;
for (int j = 0; j < global_scope_doc.constants.size(); j++) {
const DocData::ConstantDoc &curr_const_doc = global_scope_doc.constants[j];
if (curr_const_doc.name == constant_name) {
const_doc = &curr_const_doc;
break;
}
}
int64_t constant_value = CoreConstants::get_global_constant_value(i);
StringName enum_name = CoreConstants::get_global_constant_enum(i);
ConstantInterface iconstant(constant_name, snake_to_pascal_case(constant_name, true), constant_value);
iconstant.const_doc = const_doc;
if (enum_name != StringName()) {
EnumInterface ienum(enum_name);
// TODO: ienum.is_flags is always false for core constants since they don't seem to support bitfield enums
List<EnumInterface>::Element *enum_match = global_enums.find(ienum);
if (enum_match) {
enum_match->get().constants.push_back(iconstant);
} else {
ienum.constants.push_back(iconstant);
global_enums.push_back(ienum);
}
} else {
global_constants.push_back(iconstant);
}
}
for (EnumInterface &ienum : global_enums) {
TypeInterface enum_itype;
enum_itype.is_enum = true;
enum_itype.name = ienum.cname.operator String();
enum_itype.cname = ienum.cname;
enum_itype.proxy_name = enum_itype.name;
TypeInterface::postsetup_enum_type(enum_itype);
enum_itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToInt32(%0)";
enum_itype.cs_managed_to_variant = "VariantUtils.CreateFromInt((int)%0)";
enum_types.insert(enum_itype.cname, enum_itype);
int prefix_length = _determine_enum_prefix(ienum);
// HARDCODED: The Error enum have the prefix 'ERR_' for everything except 'OK' and 'FAILED'.
if (ienum.cname == name_cache.enum_Error) {
if (prefix_length > 0) { // Just in case it ever changes
ERR_PRINT("Prefix for enum '" _STR(Error) "' is not empty.");
}
prefix_length = 1; // 'ERR_'
}
_apply_prefix_to_enum_constants(ienum, prefix_length);
}
}
// HARDCODED
List<StringName> hardcoded_enums;
hardcoded_enums.push_back("Vector2.Axis");
hardcoded_enums.push_back("Vector2i.Axis");
hardcoded_enums.push_back("Vector3.Axis");
hardcoded_enums.push_back("Vector3i.Axis");
for (const StringName &enum_cname : hardcoded_enums) {
// These enums are not generated and must be written manually (e.g.: Vector3.Axis)
// Here, we assume core types do not begin with underscore
TypeInterface enum_itype;
enum_itype.is_enum = true;
enum_itype.name = enum_cname.operator String();
enum_itype.cname = enum_cname;
enum_itype.proxy_name = enum_itype.name;
TypeInterface::postsetup_enum_type(enum_itype);
enum_itype.cs_variant_to_managed = "(%1)VariantUtils.ConvertToInt32(%0)";
enum_itype.cs_managed_to_variant = "VariantUtils.CreateFromInt((int)%0)";
enum_types.insert(enum_itype.cname, enum_itype);
}
}
void BindingsGenerator::_initialize_blacklisted_methods() {
blacklisted_methods["Object"].push_back("to_string"); // there is already ToString
blacklisted_methods["Object"].push_back("_to_string"); // override ToString instead
blacklisted_methods["Object"].push_back("_init"); // never called in C# (TODO: implement it)
}
void BindingsGenerator::_log(const char *p_format, ...) {
if (log_print_enabled) {
va_list list;
va_start(list, p_format);
OS::get_singleton()->print("%s", str_format(p_format, list).utf8().get_data());
va_end(list);
}
}
void BindingsGenerator::_initialize() {
initialized = false;
EditorHelp::generate_doc();
enum_types.clear();
_initialize_blacklisted_methods();
bool obj_type_ok = _populate_object_type_interfaces();
ERR_FAIL_COND_MSG(!obj_type_ok, "Failed to generate object type interfaces");
_populate_builtin_type_interfaces();
_populate_global_constants();
// Generate internal calls (after populating type interfaces and global constants)
for (const KeyValue<StringName, TypeInterface> &E : obj_types) {
const TypeInterface &itype = E.value;
Error err = _populate_method_icalls_table(itype);
ERR_FAIL_COND_MSG(err != OK, "Failed to generate icalls table for type: " + itype.name);
}
initialized = true;
}
static String generate_all_glue_option = "--generate-mono-glue";
static void handle_cmdline_options(String glue_dir_path) {
BindingsGenerator bindings_generator;
bindings_generator.set_log_print_enabled(true);
if (!bindings_generator.is_initialized()) {
ERR_PRINT("Failed to initialize the bindings generator");
return;
}
CRASH_COND(glue_dir_path.is_empty());
if (bindings_generator.generate_cs_api(glue_dir_path.plus_file(API_SOLUTION_NAME)) != OK) {
ERR_PRINT(generate_all_glue_option + ": Failed to generate the C# API.");
}
}
static void cleanup_and_exit_godot() {
// Exit once done
Main::cleanup(true);
::exit(0);
}
void BindingsGenerator::handle_cmdline_args(const List<String> &p_cmdline_args) {
String glue_dir_path;
const List<String>::Element *elem = p_cmdline_args.front();
while (elem) {
if (elem->get() == generate_all_glue_option) {
const List<String>::Element *path_elem = elem->next();
if (path_elem) {
glue_dir_path = path_elem->get();
elem = elem->next();
} else {
ERR_PRINT(generate_all_glue_option + ": No output directory specified (expected path to '{GODOT_ROOT}/modules/mono/glue').");
// Exit once done with invalid command line arguments
cleanup_and_exit_godot();
}
break;
}
elem = elem->next();
}
if (glue_dir_path.length()) {
handle_cmdline_options(glue_dir_path);
// Exit once done
cleanup_and_exit_godot();
}
}
#endif
|