summaryrefslogtreecommitdiff
path: root/modules/mono/csharp_script.cpp
blob: 958d72adb1e60dcee9d7703bf07ee7c6360f6f7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
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
/*************************************************************************/
/*  csharp_script.cpp                                                    */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2020 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2020 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 "csharp_script.h"

#include <mono/metadata/threads.h>
#include <stdint.h>

#include "core/debugger/engine_debugger.h"
#include "core/debugger/script_debugger.h"
#include "core/io/json.h"
#include "core/os/file_access.h"
#include "core/os/mutex.h"
#include "core/os/os.h"
#include "core/os/thread.h"
#include "core/project_settings.h"

#ifdef TOOLS_ENABLED
#include "editor/bindings_generator.h"
#include "editor/csharp_project.h"
#include "editor/editor_node.h"
#include "editor/node_dock.h"
#endif

#ifdef DEBUG_METHODS_ENABLED
#include "class_db_api_json.h"
#endif

#include "editor/editor_internal_calls.h"
#include "godotsharp_dirs.h"
#include "mono_gd/gd_mono_cache.h"
#include "mono_gd/gd_mono_class.h"
#include "mono_gd/gd_mono_marshal.h"
#include "mono_gd/gd_mono_utils.h"
#include "signal_awaiter_utils.h"
#include "utils/macros.h"
#include "utils/string_utils.h"

#define CACHED_STRING_NAME(m_var) (CSharpLanguage::get_singleton()->get_string_names().m_var)

#ifdef TOOLS_ENABLED
static bool _create_project_solution_if_needed() {
	String sln_path = GodotSharpDirs::get_project_sln_path();
	String csproj_path = GodotSharpDirs::get_project_csproj_path();

	if (!FileAccess::exists(sln_path) || !FileAccess::exists(csproj_path)) {
		// A solution does not yet exist, create a new one

		CRASH_COND(CSharpLanguage::get_singleton()->get_godotsharp_editor() == nullptr);
		return CSharpLanguage::get_singleton()->get_godotsharp_editor()->call("CreateProjectSolution");
	}

	return true;
}
#endif

CSharpLanguage *CSharpLanguage::singleton = nullptr;

String CSharpLanguage::get_name() const {
	return "C#";
}

String CSharpLanguage::get_type() const {
	return "CSharpScript";
}

String CSharpLanguage::get_extension() const {
	return "cs";
}

Error CSharpLanguage::execute_file(const String &p_path) {
	// ??
	return OK;
}

void CSharpLanguage::init() {
#ifdef DEBUG_METHODS_ENABLED
	if (OS::get_singleton()->get_cmdline_args().find("--class-db-json")) {
		class_db_api_to_json("user://class_db_api.json", ClassDB::API_CORE);
#ifdef TOOLS_ENABLED
		class_db_api_to_json("user://class_db_api_editor.json", ClassDB::API_EDITOR);
#endif
	}
#endif

	gdmono = memnew(GDMono);
	gdmono->initialize();

#if defined(TOOLS_ENABLED) && defined(DEBUG_METHODS_ENABLED)
	// Generate bindings here, before loading assemblies. 'initialize_load_assemblies' aborts
	// the applications if the api assemblies or the main tools assembly is missing, but this
	// is not a problem for BindingsGenerator as it only needs the tools project editor assembly.
	List<String> cmdline_args = OS::get_singleton()->get_cmdline_args();
	BindingsGenerator::handle_cmdline_args(cmdline_args);
#endif

#ifndef MONO_GLUE_ENABLED
	print_line("Run this binary with '--generate-mono-glue path/to/modules/mono/glue'");
#endif

	if (gdmono->is_runtime_initialized())
		gdmono->initialize_load_assemblies();

#ifdef TOOLS_ENABLED
	EditorNode::add_init_callback(&_editor_init_callback);
#endif
}

void CSharpLanguage::finish() {
	if (finalized)
		return;

	finalizing = true;

	// Make sure all script binding gchandles are released before finalizing GDMono
	for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
		CSharpScriptBinding &script_binding = E->value();

		if (!script_binding.gchandle.is_released()) {
			script_binding.gchandle.release();
			script_binding.inited = false;
		}
	}

	if (gdmono) {
		memdelete(gdmono);
		gdmono = nullptr;
	}

	// Clear here, after finalizing all domains to make sure there is nothing else referencing the elements.
	script_bindings.clear();

#ifdef DEBUG_ENABLED
	for (Map<ObjectID, int>::Element *E = unsafe_object_references.front(); E; E = E->next()) {
		const ObjectID &id = E->key();
		Object *obj = ObjectDB::get_instance(id);

		if (obj) {
			ERR_PRINT("Leaked unsafe reference to object: " + obj->to_string());
		} else {
			ERR_PRINT("Leaked unsafe reference to deleted object: " + itos(id));
		}
	}
#endif

	memdelete(managed_callable_middleman);

	finalizing = false;
	finalized = true;
}

void CSharpLanguage::get_reserved_words(List<String> *p_words) const {
	static const char *_reserved_words[] = {
		// Reserved keywords
		"abstract",
		"as",
		"base",
		"bool",
		"break",
		"byte",
		"case",
		"catch",
		"char",
		"checked",
		"class",
		"const",
		"continue",
		"decimal",
		"default",
		"delegate",
		"do",
		"double",
		"else",
		"enum",
		"event",
		"explicit",
		"extern",
		"false",
		"finally",
		"fixed",
		"float",
		"for",
		"foreach",
		"goto",
		"if",
		"implicit",
		"in",
		"int",
		"interface",
		"internal",
		"is",
		"lock",
		"long",
		"namespace",
		"new",
		"null",
		"object",
		"operator",
		"out",
		"override",
		"params",
		"private",
		"protected",
		"public",
		"readonly",
		"ref",
		"return",
		"sbyte",
		"sealed",
		"short",
		"sizeof",
		"stackalloc",
		"static",
		"string",
		"struct",
		"switch",
		"this",
		"throw",
		"true",
		"try",
		"typeof",
		"uint",
		"ulong",
		"unchecked",
		"unsafe",
		"ushort",
		"using",
		"virtual",
		"void",
		"volatile",
		"while",

		// Contextual keywords. Not reserved words, but I guess we should include
		// them because this seems to be used only for syntax highlighting.
		"add",
		"alias",
		"ascending",
		"async",
		"await",
		"by",
		"descending",
		"dynamic",
		"equals",
		"from",
		"get",
		"global",
		"group",
		"into",
		"join",
		"let",
		"nameof",
		"on",
		"orderby",
		"partial",
		"remove",
		"select",
		"set",
		"value",
		"var",
		"when",
		"where",
		"yield",
		nullptr
	};

	const char **w = _reserved_words;

	while (*w) {
		p_words->push_back(*w);
		w++;
	}
}

void CSharpLanguage::get_comment_delimiters(List<String> *p_delimiters) const {
	p_delimiters->push_back("//"); // single-line comment
	p_delimiters->push_back("/* */"); // delimited comment
}

void CSharpLanguage::get_string_delimiters(List<String> *p_delimiters) const {
	p_delimiters->push_back("' '"); // character literal
	p_delimiters->push_back("\" \""); // regular string literal
	// Verbatim string literals (`@" "`) don't render correctly, so don't highlight them.
	// Generic string highlighting suffices as a workaround for now.
}

static String get_base_class_name(const String &p_base_class_name, const String p_class_name) {
	String base_class = p_base_class_name;
	if (p_class_name == base_class) {
		base_class = "Godot." + base_class;
	}
	return base_class;
}

Ref<Script> CSharpLanguage::get_template(const String &p_class_name, const String &p_base_class_name) const {
	String script_template = "using " BINDINGS_NAMESPACE ";\n"
							 "using System;\n"
							 "\n"
							 "public class %CLASS% : %BASE%\n"
							 "{\n"
							 "    // Declare member variables here. Examples:\n"
							 "    // private int a = 2;\n"
							 "    // private string b = \"text\";\n"
							 "\n"
							 "    // Called when the node enters the scene tree for the first time.\n"
							 "    public override void _Ready()\n"
							 "    {\n"
							 "        \n"
							 "    }\n"
							 "\n"
							 "//  // Called every frame. 'delta' is the elapsed time since the previous frame.\n"
							 "//  public override void _Process(float delta)\n"
							 "//  {\n"
							 "//      \n"
							 "//  }\n"
							 "}\n";

	String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
	script_template = script_template.replace("%BASE%", base_class_name)
							  .replace("%CLASS%", p_class_name);

	Ref<CSharpScript> script;
	script.instance();
	script->set_source_code(script_template);
	script->set_name(p_class_name);

	return script;
}

bool CSharpLanguage::is_using_templates() {
	return true;
}

void CSharpLanguage::make_template(const String &p_class_name, const String &p_base_class_name, Ref<Script> &p_script) {
	String src = p_script->get_source_code();
	String base_class_name = get_base_class_name(p_base_class_name, p_class_name);
	src = src.replace("%BASE%", base_class_name)
				  .replace("%CLASS%", p_class_name)
				  .replace("%TS%", _get_indentation());
	p_script->set_source_code(src);
}

String CSharpLanguage::validate_path(const String &p_path) const {
	String class_name = p_path.get_file().get_basename();
	List<String> keywords;
	get_reserved_words(&keywords);
	if (keywords.find(class_name)) {
		return TTR("Class name can't be a reserved keyword");
	}
	return "";
}

Script *CSharpLanguage::create_script() const {
	return memnew(CSharpScript);
}

bool CSharpLanguage::has_named_classes() const {
	return false;
}

bool CSharpLanguage::supports_builtin_mode() const {
	return false;
}

#ifdef TOOLS_ENABLED
static String variant_type_to_managed_name(const String &p_var_type_name) {
	if (p_var_type_name.empty())
		return "object";

	if (!ClassDB::class_exists(p_var_type_name)) {
		return p_var_type_name;
	}

	if (p_var_type_name == Variant::get_type_name(Variant::OBJECT))
		return "Godot.Object";

	if (p_var_type_name == Variant::get_type_name(Variant::FLOAT)) {
#ifdef REAL_T_IS_DOUBLE
		return "double";
#else
		return "float";
#endif
	}

	if (p_var_type_name == Variant::get_type_name(Variant::STRING))
		return "string"; // I prefer this one >:[

	if (p_var_type_name == Variant::get_type_name(Variant::DICTIONARY))
		return "Collections.Dictionary";

	if (p_var_type_name == Variant::get_type_name(Variant::ARRAY))
		return "Collections.Array";

	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_BYTE_ARRAY))
		return "byte[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT32_ARRAY))
		return "int[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_INT64_ARRAY))
		return "long[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT32_ARRAY))
		return "float[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_FLOAT64_ARRAY))
		return "double[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_STRING_ARRAY))
		return "string[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR2_ARRAY))
		return "Vector2[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_VECTOR3_ARRAY))
		return "Vector3[]";
	if (p_var_type_name == Variant::get_type_name(Variant::PACKED_COLOR_ARRAY))
		return "Color[]";

	if (p_var_type_name == Variant::get_type_name(Variant::SIGNAL))
		return "SignalInfo";

	Variant::Type var_types[] = {
		Variant::BOOL,
		Variant::INT,
		Variant::VECTOR2,
		Variant::VECTOR2I,
		Variant::RECT2,
		Variant::RECT2I,
		Variant::VECTOR3,
		Variant::VECTOR3I,
		Variant::TRANSFORM2D,
		Variant::PLANE,
		Variant::QUAT,
		Variant::AABB,
		Variant::BASIS,
		Variant::TRANSFORM,
		Variant::COLOR,
		Variant::STRING_NAME,
		Variant::NODE_PATH,
		Variant::_RID,
		Variant::CALLABLE
	};

	for (unsigned int i = 0; i < sizeof(var_types) / sizeof(Variant::Type); i++) {
		if (p_var_type_name == Variant::get_type_name(var_types[i]))
			return p_var_type_name;
	}

	return "object";
}

String CSharpLanguage::make_function(const String &, const String &p_name, const PackedStringArray &p_args) const {
	// FIXME
	// - Due to Godot's API limitation this just appends the function to the end of the file
	// - Use fully qualified name if there is ambiguity
	String s = "private void " + p_name + "(";
	for (int i = 0; i < p_args.size(); i++) {
		const String &arg = p_args[i];

		if (i > 0)
			s += ", ";

		s += variant_type_to_managed_name(arg.get_slice(":", 1)) + " " + escape_csharp_keyword(arg.get_slice(":", 0));
	}
	s += ")\n{\n    // Replace with function body.\n}\n";

	return s;
}
#else
String CSharpLanguage::make_function(const String &, const String &, const PackedStringArray &) const {
	return String();
}
#endif

String CSharpLanguage::_get_indentation() const {
#ifdef TOOLS_ENABLED
	if (Engine::get_singleton()->is_editor_hint()) {
		bool use_space_indentation = EDITOR_DEF("text_editor/indent/type", 0);

		if (use_space_indentation) {
			int indent_size = EDITOR_DEF("text_editor/indent/size", 4);

			String space_indent = "";
			for (int i = 0; i < indent_size; i++) {
				space_indent += " ";
			}
			return space_indent;
		}
	}
#endif
	return "\t";
}

String CSharpLanguage::debug_get_error() const {
	return _debug_error;
}

int CSharpLanguage::debug_get_stack_level_count() const {
	if (_debug_parse_err_line >= 0)
		return 1;

	// TODO: StackTrace
	return 1;
}

int CSharpLanguage::debug_get_stack_level_line(int p_level) const {
	if (_debug_parse_err_line >= 0)
		return _debug_parse_err_line;

	// TODO: StackTrace
	return 1;
}

String CSharpLanguage::debug_get_stack_level_function(int p_level) const {
	if (_debug_parse_err_line >= 0)
		return String();

	// TODO: StackTrace
	return String();
}

String CSharpLanguage::debug_get_stack_level_source(int p_level) const {
	if (_debug_parse_err_line >= 0)
		return _debug_parse_err_file;

	// TODO: StackTrace
	return String();
}

Vector<ScriptLanguage::StackInfo> CSharpLanguage::debug_get_current_stack_info() {
#ifdef DEBUG_ENABLED
	// Printing an error here will result in endless recursion, so we must be careful
	static thread_local bool _recursion_flag_ = false;
	if (_recursion_flag_)
		return Vector<StackInfo>();
	_recursion_flag_ = true;
	SCOPE_EXIT { _recursion_flag_ = false; };

	GD_MONO_SCOPE_THREAD_ATTACH;

	if (!gdmono->is_runtime_initialized() || !GDMono::get_singleton()->get_core_api_assembly() || !GDMonoCache::cached_data.corlib_cache_updated)
		return Vector<StackInfo>();

	MonoObject *stack_trace = mono_object_new(mono_domain_get(), CACHED_CLASS(System_Diagnostics_StackTrace)->get_mono_ptr());

	MonoBoolean need_file_info = true;
	void *ctor_args[1] = { &need_file_info };

	CACHED_METHOD(System_Diagnostics_StackTrace, ctor_bool)->invoke_raw(stack_trace, ctor_args);

	Vector<StackInfo> si;
	si = stack_trace_get_info(stack_trace);

	return si;
#else
	return Vector<StackInfo>();
#endif
}

#ifdef DEBUG_ENABLED
Vector<ScriptLanguage::StackInfo> CSharpLanguage::stack_trace_get_info(MonoObject *p_stack_trace) {
	// Printing an error here will result in endless recursion, so we must be careful
	static thread_local bool _recursion_flag_ = false;
	if (_recursion_flag_)
		return Vector<StackInfo>();
	_recursion_flag_ = true;
	SCOPE_EXIT { _recursion_flag_ = false; };

	GD_MONO_SCOPE_THREAD_ATTACH;

	MonoException *exc = nullptr;

	MonoArray *frames = CACHED_METHOD_THUNK(System_Diagnostics_StackTrace, GetFrames).invoke(p_stack_trace, &exc);

	if (exc) {
		GDMonoUtils::debug_print_unhandled_exception(exc);
		return Vector<StackInfo>();
	}

	int frame_count = mono_array_length(frames);

	if (frame_count <= 0)
		return Vector<StackInfo>();

	Vector<StackInfo> si;
	si.resize(frame_count);

	for (int i = 0; i < frame_count; i++) {
		StackInfo &sif = si.write[i];
		MonoObject *frame = mono_array_get(frames, MonoObject *, i);

		MonoString *file_name;
		int file_line_num;
		MonoString *method_decl;
		CACHED_METHOD_THUNK(DebuggingUtils, GetStackFrameInfo).invoke(frame, &file_name, &file_line_num, &method_decl, &exc);

		if (exc) {
			GDMonoUtils::debug_print_unhandled_exception(exc);
			return Vector<StackInfo>();
		}

		// TODO
		// what if the StackFrame method is null (method_decl is empty). should we skip this frame?
		// can reproduce with a MissingMethodException on internal calls

		sif.file = GDMonoMarshal::mono_string_to_godot(file_name);
		sif.line = file_line_num;
		sif.func = GDMonoMarshal::mono_string_to_godot(method_decl);
	}

	return si;
}
#endif

void CSharpLanguage::post_unsafe_reference(Object *p_obj) {
#ifdef DEBUG_ENABLED
	MutexLock lock(unsafe_object_references_lock);
	ObjectID id = p_obj->get_instance_id();
	unsafe_object_references[id]++;
#endif
}

void CSharpLanguage::pre_unsafe_unreference(Object *p_obj) {
#ifdef DEBUG_ENABLED
	MutexLock lock(unsafe_object_references_lock);
	ObjectID id = p_obj->get_instance_id();
	Map<ObjectID, int>::Element *elem = unsafe_object_references.find(id);
	ERR_FAIL_NULL(elem);
	if (--elem->value() == 0)
		unsafe_object_references.erase(elem);
#endif
}

void CSharpLanguage::frame() {
	if (gdmono && gdmono->is_runtime_initialized() && gdmono->get_core_api_assembly() != nullptr) {
		const Ref<MonoGCHandleRef> &task_scheduler_handle = GDMonoCache::cached_data.task_scheduler_handle;

		if (task_scheduler_handle.is_valid()) {
			MonoObject *task_scheduler = task_scheduler_handle->get_target();

			if (task_scheduler) {
				MonoException *exc = nullptr;
				CACHED_METHOD_THUNK(GodotTaskScheduler, Activate).invoke(task_scheduler, &exc);

				if (exc) {
					GDMonoUtils::debug_unhandled_exception(exc);
				}
			}
		}
	}
}

struct CSharpScriptDepSort {
	// must support sorting so inheritance works properly (parent must be reloaded first)
	bool operator()(const Ref<CSharpScript> &A, const Ref<CSharpScript> &B) const {
		if (A == B)
			return false; // shouldn't happen but..
		GDMonoClass *I = B->base;
		while (I) {
			if (I == A->script_class) {
				// A is a base of B
				return true;
			}

			I = I->get_parent_class();
		}

		return false; // not a base
	}
};

void CSharpLanguage::reload_all_scripts() {
#ifdef GD_MONO_HOT_RELOAD
	if (is_assembly_reloading_needed()) {
		GD_MONO_SCOPE_THREAD_ATTACH;
		reload_assemblies(false);
	}
#endif
}

void CSharpLanguage::reload_tool_script(const Ref<Script> &p_script, bool p_soft_reload) {
	(void)p_script; // UNUSED

	CRASH_COND(!Engine::get_singleton()->is_editor_hint());

#ifdef TOOLS_ENABLED
	get_godotsharp_editor()->get_node(NodePath("HotReloadAssemblyWatcher"))->call("RestartTimer");
#endif

#ifdef GD_MONO_HOT_RELOAD
	if (is_assembly_reloading_needed()) {
		GD_MONO_SCOPE_THREAD_ATTACH;
		reload_assemblies(p_soft_reload);
	}
#endif
}

#ifdef GD_MONO_HOT_RELOAD
bool CSharpLanguage::is_assembly_reloading_needed() {
	if (!gdmono->is_runtime_initialized())
		return false;

	GDMonoAssembly *proj_assembly = gdmono->get_project_assembly();

	String appname = ProjectSettings::get_singleton()->get("application/config/name");
	String appname_safe = OS::get_singleton()->get_safe_dir_name(appname);
	if (appname_safe.empty()) {
		appname_safe = "UnnamedProject";
	}

	appname_safe += ".dll";

	if (proj_assembly) {
		String proj_asm_path = proj_assembly->get_path();

		if (!FileAccess::exists(proj_asm_path)) {
			// Maybe it wasn't loaded from the default path, so check this as well
			proj_asm_path = GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe);
			if (!FileAccess::exists(proj_asm_path))
				return false; // No assembly to load
		}

		if (FileAccess::get_modified_time(proj_asm_path) <= proj_assembly->get_modified_time())
			return false; // Already up to date
	} else {
		if (!FileAccess::exists(GodotSharpDirs::get_res_temp_assemblies_dir().plus_file(appname_safe)))
			return false; // No assembly to load
	}

	return true;
}

void CSharpLanguage::reload_assemblies(bool p_soft_reload) {
	if (!gdmono->is_runtime_initialized())
		return;

	// There is no soft reloading with Mono. It's always hard reloading.

	List<Ref<CSharpScript>> scripts;

	{
		MutexLock lock(script_instances_mutex);

		for (SelfList<CSharpScript> *elem = script_list.first(); elem; elem = elem->next()) {
			// Cast to CSharpScript to avoid being erased by accident
			scripts.push_back(Ref<CSharpScript>(elem->self()));
		}
	}

	scripts.sort_custom<CSharpScriptDepSort>(); // Update in inheritance dependency order

	// Serialize managed callables
	{
		MutexLock lock(ManagedCallable::instances_mutex);

		for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
			ManagedCallable *managed_callable = elem->self();

			MonoDelegate *delegate = (MonoDelegate *)managed_callable->delegate_handle.get_target();

			Array serialized_data;
			MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);

			MonoException *exc = nullptr;
			bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TrySerializeDelegate).invoke(delegate, managed_serialized_data, &exc);

			if (exc) {
				GDMonoUtils::debug_print_unhandled_exception(exc);
				continue;
			}

			if (success) {
				ManagedCallable::instances_pending_reload.insert(managed_callable, serialized_data);
			} else if (OS::get_singleton()->is_stdout_verbose()) {
				OS::get_singleton()->print("Failed to serialize delegate\n");
			}
		}
	}

	List<Ref<CSharpScript>> to_reload;

	// We need to keep reference instances alive during reloading
	List<Ref<Reference>> ref_instances;

	for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
		CSharpScriptBinding &script_binding = E->value();
		Reference *ref = Object::cast_to<Reference>(script_binding.owner);
		if (ref) {
			ref_instances.push_back(Ref<Reference>(ref));
		}
	}

	// As scripts are going to be reloaded, must proceed without locking here

	for (List<Ref<CSharpScript>>::Element *E = scripts.front(); E; E = E->next()) {
		Ref<CSharpScript> &script = E->get();

		to_reload.push_back(script);

		if (script->get_path().empty()) {
			script->tied_class_name_for_reload = script->script_class->get_name_for_lookup();
			script->tied_class_namespace_for_reload = script->script_class->get_namespace();
		}

		// Script::instances are deleted during managed object disposal, which happens on domain finalize.
		// Only placeholders are kept. Therefore we need to keep a copy before that happens.

		for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
			Object *obj = F->get();
			script->pending_reload_instances.insert(obj->get_instance_id());

			Reference *ref = Object::cast_to<Reference>(obj);
			if (ref) {
				ref_instances.push_back(Ref<Reference>(ref));
			}
		}

#ifdef TOOLS_ENABLED
		for (Set<PlaceHolderScriptInstance *>::Element *F = script->placeholders.front(); F; F = F->next()) {
			Object *obj = F->get()->get_owner();
			script->pending_reload_instances.insert(obj->get_instance_id());

			Reference *ref = Object::cast_to<Reference>(obj);
			if (ref) {
				ref_instances.push_back(Ref<Reference>(ref));
			}
		}
#endif

		// Save state and remove script from instances
		Map<ObjectID, CSharpScript::StateBackup> &owners_map = script->pending_reload_state;

		for (Set<Object *>::Element *F = script->instances.front(); F; F = F->next()) {
			Object *obj = F->get();

			ERR_CONTINUE(!obj->get_script_instance());

			CSharpInstance *csi = static_cast<CSharpInstance *>(obj->get_script_instance());

			// Call OnBeforeSerialize
			if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
				obj->get_script_instance()->call_multilevel(string_names.on_before_serialize);

			// Save instance info
			CSharpScript::StateBackup state;

			// TODO: Proper state backup (Not only variants, serialize managed state of scripts)
			csi->get_properties_state_for_reloading(state.properties);
			csi->get_event_signals_state_for_reloading(state.event_signals);

			owners_map[obj->get_instance_id()] = state;
		}
	}

	// After the state of all instances is saved, clear scripts and script instances
	for (List<Ref<CSharpScript>>::Element *E = scripts.front(); E; E = E->next()) {
		Ref<CSharpScript> &script = E->get();

		while (script->instances.front()) {
			Object *obj = script->instances.front()->get();
			obj->set_script(REF()); // Remove script and existing script instances (placeholder are not removed before domain reload)
		}

		script->_clear();
	}

	// Do domain reload
	if (gdmono->reload_scripts_domain() != OK) {
		// Failed to reload the scripts domain
		// Make sure to add the scripts back to their owners before returning
		for (List<Ref<CSharpScript>>::Element *E = to_reload.front(); E; E = E->next()) {
			Ref<CSharpScript> scr = E->get();

			for (const Map<ObjectID, CSharpScript::StateBackup>::Element *F = scr->pending_reload_state.front(); F; F = F->next()) {
				Object *obj = ObjectDB::get_instance(F->key());

				if (!obj)
					continue;

				ObjectID obj_id = obj->get_instance_id();

				// Use a placeholder for now to avoid losing the state when saving a scene

				obj->set_script(scr);

				PlaceHolderScriptInstance *placeholder = scr->placeholder_instance_create(obj);
				obj->set_script_instance(placeholder);

#ifdef TOOLS_ENABLED
				// Even though build didn't fail, this tells the placeholder to keep properties and
				// it allows using property_set_fallback for restoring the state without a valid script.
				scr->placeholder_fallback_enabled = true;
#endif

				// Restore Variant properties state, it will be kept by the placeholder until the next script reloading
				for (List<Pair<StringName, Variant>>::Element *G = scr->pending_reload_state[obj_id].properties.front(); G; G = G->next()) {
					placeholder->property_set_fallback(G->get().first, G->get().second, nullptr);
				}

				scr->pending_reload_state.erase(obj_id);
			}
		}

		return;
	}

	List<Ref<CSharpScript>> to_reload_state;

	for (List<Ref<CSharpScript>>::Element *E = to_reload.front(); E; E = E->next()) {
		Ref<CSharpScript> script = E->get();

		if (!script->get_path().empty()) {
#ifdef TOOLS_ENABLED
			script->exports_invalidated = true;
#endif
			script->signals_invalidated = true;

			script->reload(p_soft_reload);
			script->update_exports();

			if (!script->valid) {
				script->pending_reload_instances.clear();
				continue;
			}
		} else {
			const StringName &class_namespace = script->tied_class_namespace_for_reload;
			const StringName &class_name = script->tied_class_name_for_reload;
			GDMonoAssembly *project_assembly = gdmono->get_project_assembly();

			// Search in project and tools assemblies first as those are the most likely to have the class
			GDMonoClass *script_class = (project_assembly ? project_assembly->get_class(class_namespace, class_name) : nullptr);

#ifdef TOOLS_ENABLED
			if (!script_class) {
				GDMonoAssembly *tools_assembly = gdmono->get_tools_assembly();
				script_class = (tools_assembly ? tools_assembly->get_class(class_namespace, class_name) : nullptr);
			}
#endif

			if (!script_class) {
				script_class = gdmono->get_class(class_namespace, class_name);
			}

			if (!script_class) {
				// The class was removed, can't reload
				script->pending_reload_instances.clear();
				continue;
			}

			bool obj_type = CACHED_CLASS(GodotObject)->is_assignable_from(script_class);
			if (!obj_type) {
				// The class no longer inherits Godot.Object, can't reload
				script->pending_reload_instances.clear();
				continue;
			}

			GDMonoClass *native = GDMonoUtils::get_class_native_base(script_class);

			CSharpScript::initialize_for_managed_type(script, script_class, native);
		}

		StringName native_name = NATIVE_GDMONOCLASS_NAME(script->native);

		{
			for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
				ObjectID obj_id = F->get();
				Object *obj = ObjectDB::get_instance(obj_id);

				if (!obj) {
					script->pending_reload_state.erase(obj_id);
					continue;
				}

				if (!ClassDB::is_parent_class(obj->get_class_name(), native_name)) {
					// No longer inherits the same compatible type, can't reload
					script->pending_reload_state.erase(obj_id);
					continue;
				}

				ScriptInstance *si = obj->get_script_instance();

#ifdef TOOLS_ENABLED
				if (si) {
					// If the script instance is not null, then it must be a placeholder.
					// Non-placeholder script instances are removed in godot_icall_Object_Disposed.
					CRASH_COND(!si->is_placeholder());

					if (script->is_tool() || ScriptServer::is_scripting_enabled()) {
						// Replace placeholder with a script instance

						CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];

						// Backup placeholder script instance state before replacing it with a script instance
						si->get_property_state(state_backup.properties);

						ScriptInstance *script_instance = script->instance_create(obj);

						if (script_instance) {
							script->placeholders.erase(static_cast<PlaceHolderScriptInstance *>(si));
							obj->set_script_instance(script_instance);
						}
					}

					continue;
				}
#else
				CRASH_COND(si != nullptr);
#endif
				// Re-create script instance
				obj->set_script(script); // will create the script instance as well
			}
		}

		to_reload_state.push_back(script);
	}

	for (List<Ref<CSharpScript>>::Element *E = to_reload_state.front(); E; E = E->next()) {
		Ref<CSharpScript> script = E->get();

		for (Set<ObjectID>::Element *F = script->pending_reload_instances.front(); F; F = F->next()) {
			ObjectID obj_id = F->get();
			Object *obj = ObjectDB::get_instance(obj_id);

			if (!obj) {
				script->pending_reload_state.erase(obj_id);
				continue;
			}

			ERR_CONTINUE(!obj->get_script_instance());

			// TODO: Restore serialized state

			CSharpScript::StateBackup &state_backup = script->pending_reload_state[obj_id];

			for (List<Pair<StringName, Variant>>::Element *G = state_backup.properties.front(); G; G = G->next()) {
				obj->get_script_instance()->set(G->get().first, G->get().second);
			}

			CSharpInstance *csi = CAST_CSHARP_INSTANCE(obj->get_script_instance());

			if (csi) {
				for (List<Pair<StringName, Array>>::Element *G = state_backup.event_signals.front(); G; G = G->next()) {
					const StringName &name = G->get().first;
					const Array &serialized_data = G->get().second;

					Map<StringName, CSharpScript::EventSignal>::Element *match = script->event_signals.find(name);

					if (!match) {
						// The event or its signal attribute were removed
						continue;
					}

					const CSharpScript::EventSignal &event_signal = match->value();

					MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
					MonoDelegate *delegate = nullptr;

					MonoException *exc = nullptr;
					bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TryDeserializeDelegate).invoke(managed_serialized_data, &delegate, &exc);

					if (exc) {
						GDMonoUtils::debug_print_unhandled_exception(exc);
						continue;
					}

					if (success) {
						ERR_CONTINUE(delegate == nullptr);
						event_signal.field->set_value(csi->get_mono_object(), (MonoObject *)delegate);
					} else if (OS::get_singleton()->is_stdout_verbose()) {
						OS::get_singleton()->print("Failed to deserialize event signal delegate\n");
					}
				}

				// Call OnAfterDeserialization
				if (csi->script->script_class->implements_interface(CACHED_CLASS(ISerializationListener)))
					obj->get_script_instance()->call_multilevel(string_names.on_after_deserialize);
			}
		}

		script->pending_reload_instances.clear();
	}

	// Deserialize managed callables
	{
		MutexLock lock(ManagedCallable::instances_mutex);

		for (Map<ManagedCallable *, Array>::Element *elem = ManagedCallable::instances_pending_reload.front(); elem; elem = elem->next()) {
			ManagedCallable *managed_callable = elem->key();
			const Array &serialized_data = elem->value();

			MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);
			MonoDelegate *delegate = nullptr;

			MonoException *exc = nullptr;
			bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TryDeserializeDelegate).invoke(managed_serialized_data, &delegate, &exc);

			if (exc) {
				GDMonoUtils::debug_print_unhandled_exception(exc);
				continue;
			}

			if (success) {
				ERR_CONTINUE(delegate == nullptr);
				managed_callable->set_delegate(delegate);
			} else if (OS::get_singleton()->is_stdout_verbose()) {
				OS::get_singleton()->print("Failed to deserialize delegate\n");
			}
		}

		ManagedCallable::instances_pending_reload.clear();
	}

#ifdef TOOLS_ENABLED
	// FIXME: Hack to refresh editor in order to display new properties and signals. See if there is a better alternative.
	if (Engine::get_singleton()->is_editor_hint()) {
		EditorNode::get_singleton()->get_inspector()->update_tree();
		NodeDock::singleton->update_lists();
	}
#endif
}
#endif

void CSharpLanguage::_load_scripts_metadata() {
	scripts_metadata.clear();

	String scripts_metadata_filename = "scripts_metadata.";

#ifdef TOOLS_ENABLED
	scripts_metadata_filename += Engine::get_singleton()->is_editor_hint() ? "editor" : "editor_player";
#else
#ifdef DEBUG_ENABLED
	scripts_metadata_filename += "debug";
#else
	scripts_metadata_filename += "release";
#endif
#endif

	String scripts_metadata_path = GodotSharpDirs::get_res_metadata_dir().plus_file(scripts_metadata_filename);

	if (FileAccess::exists(scripts_metadata_path)) {
		String old_json;

		Error ferr = read_all_file_utf8(scripts_metadata_path, old_json);

		ERR_FAIL_COND(ferr != OK);

		Variant old_dict_var;
		String err_str;
		int err_line;
		Error json_err = JSON::parse(old_json, old_dict_var, err_str, err_line);
		if (json_err != OK) {
			ERR_PRINT("Failed to parse metadata file: '" + err_str + "' (" + String::num_int64(err_line) + ").");
			return;
		}

		scripts_metadata = old_dict_var.operator Dictionary();
		scripts_metadata_invalidated = false;

		print_verbose("Successfully loaded scripts metadata");
	} else {
		if (!Engine::get_singleton()->is_editor_hint()) {
			ERR_PRINT("Missing scripts metadata file.");
		}
	}
}

void CSharpLanguage::get_recognized_extensions(List<String> *p_extensions) const {
	p_extensions->push_back("cs");
}

#ifdef TOOLS_ENABLED
Error CSharpLanguage::open_in_external_editor(const Ref<Script> &p_script, int p_line, int p_col) {
	return (Error)(int)get_godotsharp_editor()->call("OpenInExternalEditor", p_script, p_line, p_col);
}

bool CSharpLanguage::overrides_external_editor() {
	return get_godotsharp_editor()->call("OverridesExternalEditor");
}
#endif

void CSharpLanguage::thread_enter() {
#if 0
	if (gdmono->is_runtime_initialized()) {
		GDMonoUtils::attach_current_thread();
	}
#endif
}

void CSharpLanguage::thread_exit() {
#if 0
	if (gdmono->is_runtime_initialized()) {
		GDMonoUtils::detach_current_thread();
	}
#endif
}

bool CSharpLanguage::debug_break_parse(const String &p_file, int p_line, const String &p_error) {
	// Not a parser error in our case, but it's still used for other type of errors
	if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
		_debug_parse_err_line = p_line;
		_debug_parse_err_file = p_file;
		_debug_error = p_error;
		EngineDebugger::get_script_debugger()->debug(this, false, true);
		return true;
	} else {
		return false;
	}
}

bool CSharpLanguage::debug_break(const String &p_error, bool p_allow_continue) {
	if (EngineDebugger::is_active() && Thread::get_caller_id() == Thread::get_main_id()) {
		_debug_parse_err_line = -1;
		_debug_parse_err_file = "";
		_debug_error = p_error;
		EngineDebugger::get_script_debugger()->debug(this, p_allow_continue);
		return true;
	} else {
		return false;
	}
}

void CSharpLanguage::_on_scripts_domain_unloaded() {
	for (Map<Object *, CSharpScriptBinding>::Element *E = script_bindings.front(); E; E = E->next()) {
		CSharpScriptBinding &script_binding = E->value();
		script_binding.gchandle.release();
		script_binding.inited = false;
	}

	{
		MutexLock lock(ManagedCallable::instances_mutex);

		for (SelfList<ManagedCallable> *elem = ManagedCallable::instances.first(); elem; elem = elem->next()) {
			ManagedCallable *managed_callable = elem->self();
			managed_callable->delegate_handle.release();
			managed_callable->delegate_invoke = nullptr;
		}
	}

	scripts_metadata_invalidated = true;
}

#ifdef TOOLS_ENABLED
void CSharpLanguage::_editor_init_callback() {
	register_editor_internal_calls();

	// Initialize GodotSharpEditor

	GDMonoClass *editor_klass = GDMono::get_singleton()->get_tools_assembly()->get_class("GodotTools", "GodotSharpEditor");
	CRASH_COND(editor_klass == nullptr);

	MonoObject *mono_object = mono_object_new(mono_domain_get(), editor_klass->get_mono_ptr());
	CRASH_COND(mono_object == nullptr);

	MonoException *exc = nullptr;
	GDMonoUtils::runtime_object_init(mono_object, editor_klass, &exc);
	UNHANDLED_EXCEPTION(exc);

	EditorPlugin *godotsharp_editor = Object::cast_to<EditorPlugin>(GDMonoMarshal::mono_object_to_variant(mono_object));
	CRASH_COND(godotsharp_editor == nullptr);

	// Enable it as a plugin
	EditorNode::add_editor_plugin(godotsharp_editor);
	godotsharp_editor->enable_plugin();

	get_singleton()->godotsharp_editor = godotsharp_editor;
}
#endif

void CSharpLanguage::set_language_index(int p_idx) {
	ERR_FAIL_COND(lang_idx != -1);
	lang_idx = p_idx;
}

void CSharpLanguage::release_script_gchandle(MonoGCHandleData &p_gchandle) {
	if (!p_gchandle.is_released()) { // Do not lock unnecessarily
		MutexLock lock(get_singleton()->script_gchandle_release_mutex);
		p_gchandle.release();
	}
}

void CSharpLanguage::release_script_gchandle(MonoObject *p_expected_obj, MonoGCHandleData &p_gchandle) {
	uint32_t pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(p_expected_obj); // We might lock after this, so pin it

	if (!p_gchandle.is_released()) { // Do not lock unnecessarily
		MutexLock lock(get_singleton()->script_gchandle_release_mutex);

		MonoObject *target = p_gchandle.get_target();

		// We release the gchandle if it points to the MonoObject* we expect (otherwise it was
		// already released and could have been replaced) or if we can't get its target MonoObject*
		// (which doesn't necessarily mean it was released, and we want it released in order to
		// avoid locking other threads unnecessarily).
		if (target == p_expected_obj || target == nullptr) {
			p_gchandle.release();
		}
	}

	GDMonoUtils::free_gchandle(pinned_gchandle);
}

CSharpLanguage::CSharpLanguage() {
	ERR_FAIL_COND_MSG(singleton, "C# singleton already exist.");
	singleton = this;
}

CSharpLanguage::~CSharpLanguage() {
	finish();
	singleton = nullptr;
}

bool CSharpLanguage::setup_csharp_script_binding(CSharpScriptBinding &r_script_binding, Object *p_object) {
#ifdef DEBUG_ENABLED
	// I don't trust you
	if (p_object->get_script_instance()) {
		CSharpInstance *csharp_instance = CAST_CSHARP_INSTANCE(p_object->get_script_instance());
		CRASH_COND(csharp_instance != nullptr && !csharp_instance->is_destructing_script_instance());
	}
#endif

	StringName type_name = p_object->get_class_name();

	// ¯\_(ツ)_/¯
	const ClassDB::ClassInfo *classinfo = ClassDB::classes.getptr(type_name);
	while (classinfo && !classinfo->exposed)
		classinfo = classinfo->inherits_ptr;
	ERR_FAIL_NULL_V(classinfo, false);
	type_name = classinfo->name;

	GDMonoClass *type_class = GDMonoUtils::type_get_proxy_class(type_name);

	ERR_FAIL_NULL_V(type_class, false);

	MonoObject *mono_object = GDMonoUtils::create_managed_for_godot_object(type_class, type_name, p_object);

	ERR_FAIL_NULL_V(mono_object, false);

	r_script_binding.inited = true;
	r_script_binding.type_name = type_name;
	r_script_binding.wrapper_class = type_class; // cache
	r_script_binding.gchandle = MonoGCHandleData::new_strong_handle(mono_object);
	r_script_binding.owner = p_object;

	// Tie managed to unmanaged
	Reference *ref = Object::cast_to<Reference>(p_object);

	if (ref) {
		// Unsafe refcount increment. The managed instance also counts as a reference.
		// This way if the unmanaged world has no references to our owner
		// but the managed instance is alive, the refcount will be 1 instead of 0.
		// See: godot_icall_Reference_Dtor(MonoObject *p_obj, Object *p_ptr)

		ref->reference();
		CSharpLanguage::get_singleton()->post_unsafe_reference(ref);
	}

	return true;
}

void *CSharpLanguage::alloc_instance_binding_data(Object *p_object) {
	MutexLock lock(language_bind_mutex);

	Map<Object *, CSharpScriptBinding>::Element *match = script_bindings.find(p_object);
	if (match)
		return (void *)match;

	CSharpScriptBinding script_binding;

	if (!setup_csharp_script_binding(script_binding, p_object))
		return nullptr;

	return (void *)insert_script_binding(p_object, script_binding);
}

Map<Object *, CSharpScriptBinding>::Element *CSharpLanguage::insert_script_binding(Object *p_object, const CSharpScriptBinding &p_script_binding) {
	return script_bindings.insert(p_object, p_script_binding);
}

void CSharpLanguage::free_instance_binding_data(void *p_data) {
	if (GDMono::get_singleton() == nullptr) {
#ifdef DEBUG_ENABLED
		CRASH_COND(!script_bindings.empty());
#endif
		// Mono runtime finalized, all the gchandle bindings were already released
		return;
	}

	if (finalizing)
		return; // inside CSharpLanguage::finish(), all the gchandle bindings are released there

	GD_MONO_ASSERT_THREAD_ATTACHED;

	{
		MutexLock lock(language_bind_mutex);

		Map<Object *, CSharpScriptBinding>::Element *data = (Map<Object *, CSharpScriptBinding>::Element *)p_data;

		CSharpScriptBinding &script_binding = data->value();

		if (script_binding.inited) {
			// Set the native instance field to IntPtr.Zero, if not yet garbage collected.
			// This is done to avoid trying to dispose the native instance from Dispose(bool).
			MonoObject *mono_object = script_binding.gchandle.get_target();
			if (mono_object) {
				CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, nullptr);
			}
			script_binding.gchandle.release();
		}

		script_bindings.erase(data);
	}
}

void CSharpLanguage::refcount_incremented_instance_binding(Object *p_object) {
	Reference *ref_owner = Object::cast_to<Reference>(p_object);

#ifdef DEBUG_ENABLED
	CRASH_COND(!ref_owner);
	CRASH_COND(!p_object->has_script_instance_binding(get_language_index()));
#endif

	void *data = p_object->get_script_instance_binding(get_language_index());
	CRASH_COND(!data);

	CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
	MonoGCHandleData &gchandle = script_binding.gchandle;

	if (!script_binding.inited)
		return;

	if (ref_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
		GD_MONO_SCOPE_THREAD_ATTACH;

		// The reference count was increased after the managed side was the only one referencing our owner.
		// This means the owner is being referenced again by the unmanaged side,
		// so the owner must hold the managed side alive again to avoid it from being GCed.

		MonoObject *target = gchandle.get_target();
		if (!target)
			return; // Called after the managed side was collected, so nothing to do here

		// Release the current weak handle and replace it with a strong handle.
		MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(target);
		gchandle.release();
		gchandle = strong_gchandle;
	}
}

bool CSharpLanguage::refcount_decremented_instance_binding(Object *p_object) {
	Reference *ref_owner = Object::cast_to<Reference>(p_object);

#ifdef DEBUG_ENABLED
	CRASH_COND(!ref_owner);
	CRASH_COND(!p_object->has_script_instance_binding(get_language_index()));
#endif

	void *data = p_object->get_script_instance_binding(get_language_index());
	CRASH_COND(!data);

	CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
	MonoGCHandleData &gchandle = script_binding.gchandle;

	int refcount = ref_owner->reference_get_count();

	if (!script_binding.inited)
		return refcount == 0;

	if (refcount == 1 && !gchandle.is_released() && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
		GD_MONO_SCOPE_THREAD_ATTACH;

		// If owner owner is no longer referenced by the unmanaged side,
		// the managed instance takes responsibility of deleting the owner when GCed.

		MonoObject *target = gchandle.get_target();
		if (!target)
			return refcount == 0; // Called after the managed side was collected, so nothing to do here

		// Release the current strong handle and replace it with a weak handle.
		MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(target);
		gchandle.release();
		gchandle = weak_gchandle;

		return false;
	}

	return refcount == 0;
}

CSharpInstance *CSharpInstance::create_for_managed_type(Object *p_owner, CSharpScript *p_script, const MonoGCHandleData &p_gchandle) {
	CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(p_script)));

	Reference *ref = Object::cast_to<Reference>(p_owner);

	instance->base_ref = ref != nullptr;
	instance->owner = p_owner;
	instance->gchandle = p_gchandle;

	if (instance->base_ref)
		instance->_reference_owner_unsafe();

	p_script->instances.insert(p_owner);

	return instance;
}

MonoObject *CSharpInstance::get_mono_object() const {
	ERR_FAIL_COND_V(gchandle.is_released(), nullptr);
	return gchandle.get_target();
}

Object *CSharpInstance::get_owner() {
	return owner;
}

bool CSharpInstance::set(const StringName &p_name, const Variant &p_value) {
	ERR_FAIL_COND_V(!script.is_valid(), false);

	GD_MONO_SCOPE_THREAD_ATTACH;

	MonoObject *mono_object = get_mono_object();
	ERR_FAIL_NULL_V(mono_object, false);

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		GDMonoField *field = top->get_field(p_name);

		if (field) {
			field->set_value_from_variant(mono_object, p_value);
			return true;
		}

		GDMonoProperty *property = top->get_property(p_name);

		if (property) {
			property->set_value(mono_object, GDMonoMarshal::variant_to_mono_object(p_value, property->get_type()));
			return true;
		}

		top = top->get_parent_class();
	}

	// Call _set

	top = script->script_class;

	while (top && top != script->native) {
		GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_set), 2);

		if (method) {
			Variant name = p_name;
			const Variant *args[2] = { &name, &p_value };

			MonoObject *ret = method->invoke(mono_object, args);

			if (ret && GDMonoMarshal::unbox<MonoBoolean>(ret))
				return true;

			break;
		}

		top = top->get_parent_class();
	}

	return false;
}

bool CSharpInstance::get(const StringName &p_name, Variant &r_ret) const {
	ERR_FAIL_COND_V(!script.is_valid(), false);

	GD_MONO_SCOPE_THREAD_ATTACH;

	MonoObject *mono_object = get_mono_object();
	ERR_FAIL_NULL_V(mono_object, false);

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		GDMonoField *field = top->get_field(p_name);

		if (field) {
			MonoObject *value = field->get_value(mono_object);
			r_ret = GDMonoMarshal::mono_object_to_variant(value);
			return true;
		}

		GDMonoProperty *property = top->get_property(p_name);

		if (property) {
			MonoException *exc = nullptr;
			MonoObject *value = property->get_value(mono_object, &exc);
			if (exc) {
				r_ret = Variant();
				GDMonoUtils::set_pending_exception(exc);
			} else {
				r_ret = GDMonoMarshal::mono_object_to_variant(value);
			}
			return true;
		}

		top = top->get_parent_class();
	}

	// Call _get

	top = script->script_class;

	while (top && top != script->native) {
		GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get), 1);

		if (method) {
			Variant name = p_name;
			const Variant *args[1] = { &name };

			MonoObject *ret = method->invoke(mono_object, args);

			if (ret) {
				r_ret = GDMonoMarshal::mono_object_to_variant(ret);
				return true;
			}

			break;
		}

		top = top->get_parent_class();
	}

	return false;
}

void CSharpInstance::get_properties_state_for_reloading(List<Pair<StringName, Variant>> &r_state) {
	List<PropertyInfo> pinfo;
	get_property_list(&pinfo);

	for (List<PropertyInfo>::Element *E = pinfo.front(); E; E = E->next()) {
		Pair<StringName, Variant> state_pair;
		state_pair.first = E->get().name;

		ManagedType managedType;

		GDMonoField *field = script->script_class->get_field(state_pair.first);
		if (!field)
			continue; // Properties ignored. We get the property baking fields instead.

		managedType = field->get_type();

		if (GDMonoMarshal::managed_to_variant_type(managedType) != Variant::NIL) { // If we can marshal it
			if (get(state_pair.first, state_pair.second)) {
				r_state.push_back(state_pair);
			}
		}
	}
}

void CSharpInstance::get_event_signals_state_for_reloading(List<Pair<StringName, Array>> &r_state) {
	MonoObject *owner_managed = get_mono_object();
	ERR_FAIL_NULL(owner_managed);

	for (const Map<StringName, CSharpScript::EventSignal>::Element *E = script->event_signals.front(); E; E = E->next()) {
		const CSharpScript::EventSignal &event_signal = E->value();

		MonoDelegate *delegate_field_value = (MonoDelegate *)event_signal.field->get_value(owner_managed);
		if (!delegate_field_value)
			continue; // Empty

		Array serialized_data;
		MonoObject *managed_serialized_data = GDMonoMarshal::variant_to_mono_object(serialized_data);

		MonoException *exc = nullptr;
		bool success = (bool)CACHED_METHOD_THUNK(DelegateUtils, TrySerializeDelegate).invoke(delegate_field_value, managed_serialized_data, &exc);

		if (exc) {
			GDMonoUtils::debug_print_unhandled_exception(exc);
			continue;
		}

		if (success) {
			r_state.push_back(Pair<StringName, Array>(event_signal.field->get_name(), serialized_data));
		} else if (OS::get_singleton()->is_stdout_verbose()) {
			OS::get_singleton()->print("Failed to serialize event signal delegate\n");
		}
	}
}

void CSharpInstance::get_property_list(List<PropertyInfo> *p_properties) const {
	for (Map<StringName, PropertyInfo>::Element *E = script->member_info.front(); E; E = E->next()) {
		p_properties->push_back(E->value());
	}

	// Call _get_property_list

	ERR_FAIL_COND(!script.is_valid());

	GD_MONO_SCOPE_THREAD_ATTACH;

	MonoObject *mono_object = get_mono_object();
	ERR_FAIL_NULL(mono_object);

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		GDMonoMethod *method = top->get_method(CACHED_STRING_NAME(_get_property_list), 0);

		if (method) {
			MonoObject *ret = method->invoke(mono_object);

			if (ret) {
				Array array = Array(GDMonoMarshal::mono_object_to_variant(ret));
				for (int i = 0, size = array.size(); i < size; i++)
					p_properties->push_back(PropertyInfo::from_dict(array.get(i)));
				return;
			}

			break;
		}

		top = top->get_parent_class();
	}
}

Variant::Type CSharpInstance::get_property_type(const StringName &p_name, bool *r_is_valid) const {
	if (script->member_info.has(p_name)) {
		if (r_is_valid)
			*r_is_valid = true;
		return script->member_info[p_name].type;
	}

	if (r_is_valid)
		*r_is_valid = false;

	return Variant::NIL;
}

bool CSharpInstance::has_method(const StringName &p_method) const {
	if (!script.is_valid())
		return false;

	GD_MONO_SCOPE_THREAD_ATTACH;

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		if (top->has_fetched_method_unknown_params(p_method)) {
			return true;
		}

		top = top->get_parent_class();
	}

	return false;
}

Variant CSharpInstance::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
	ERR_FAIL_COND_V(!script.is_valid(), Variant());

	GD_MONO_SCOPE_THREAD_ATTACH;

	MonoObject *mono_object = get_mono_object();

	if (!mono_object) {
		r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
		ERR_FAIL_V(Variant());
	}

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		GDMonoMethod *method = top->get_method(p_method, p_argcount);

		if (method) {
			MonoObject *return_value = method->invoke(mono_object, p_args);

			r_error.error = Callable::CallError::CALL_OK;

			if (return_value) {
				return GDMonoMarshal::mono_object_to_variant(return_value);
			} else {
				return Variant();
			}
		}

		top = top->get_parent_class();
	}

	r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;

	return Variant();
}

void CSharpInstance::call_multilevel(const StringName &p_method, const Variant **p_args, int p_argcount) {
	GD_MONO_SCOPE_THREAD_ATTACH;

	if (script.is_valid()) {
		MonoObject *mono_object = get_mono_object();

		ERR_FAIL_NULL(mono_object);

		_call_multilevel(mono_object, p_method, p_args, p_argcount);
	}
}

void CSharpInstance::_call_multilevel(MonoObject *p_mono_object, const StringName &p_method, const Variant **p_args, int p_argcount) {
	GD_MONO_ASSERT_THREAD_ATTACHED;

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		GDMonoMethod *method = top->get_method(p_method, p_argcount);

		if (method) {
			method->invoke(p_mono_object, p_args);
			return;
		}

		top = top->get_parent_class();
	}
}

void CSharpInstance::call_multilevel_reversed(const StringName &p_method, const Variant **p_args, int p_argcount) {
	// Sorry, the method is the one that controls the call order

	call_multilevel(p_method, p_args, p_argcount);
}

bool CSharpInstance::_reference_owner_unsafe() {
#ifdef DEBUG_ENABLED
	CRASH_COND(!base_ref);
	CRASH_COND(owner == nullptr);
	CRASH_COND(unsafe_referenced); // already referenced
#endif

	// Unsafe refcount increment. The managed instance also counts as a reference.
	// This way if the unmanaged world has no references to our owner
	// but the managed instance is alive, the refcount will be 1 instead of 0.
	// See: _unreference_owner_unsafe()

	// May not me referenced yet, so we must use init_ref() instead of reference()
	if (static_cast<Reference *>(owner)->init_ref()) {
		CSharpLanguage::get_singleton()->post_unsafe_reference(owner);
		unsafe_referenced = true;
	}

	return unsafe_referenced;
}

bool CSharpInstance::_unreference_owner_unsafe() {
#ifdef DEBUG_ENABLED
	CRASH_COND(!base_ref);
	CRASH_COND(owner == nullptr);
#endif

	if (!unsafe_referenced)
		return false; // Already unreferenced

	unsafe_referenced = false;

	// Called from CSharpInstance::mono_object_disposed() or ~CSharpInstance()

	// Unsafe refcount decrement. The managed instance also counts as a reference.
	// See: _reference_owner_unsafe()

	// Destroying the owner here means self destructing, so we defer the owner destruction to the caller.
	CSharpLanguage::get_singleton()->pre_unsafe_unreference(owner);
	return static_cast<Reference *>(owner)->unreference();
}

MonoObject *CSharpInstance::_internal_new_managed() {
	// Search the constructor first, to fail with an error if it's not found before allocating anything else.
	GDMonoMethod *ctor = script->script_class->get_method(CACHED_STRING_NAME(dotctor), 0);
	ERR_FAIL_NULL_V_MSG(ctor, nullptr,
			"Cannot create script instance because the class does not define a parameterless constructor: '" + script->get_path() + "'.");

	CSharpLanguage::get_singleton()->release_script_gchandle(gchandle);

	ERR_FAIL_NULL_V(owner, nullptr);
	ERR_FAIL_COND_V(script.is_null(), nullptr);

	MonoObject *mono_object = mono_object_new(mono_domain_get(), script->script_class->get_mono_ptr());

	if (!mono_object) {
		// Important to clear this before destroying the script instance here
		script = Ref<CSharpScript>();

		bool die = _unreference_owner_unsafe();
		// Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
		CRASH_COND(die == true);

		owner = nullptr;

		ERR_FAIL_V_MSG(nullptr, "Failed to allocate memory for the object.");
	}

	// Tie managed to unmanaged
	gchandle = MonoGCHandleData::new_strong_handle(mono_object);

	if (base_ref)
		_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)

	CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, owner);

	// Construct
	ctor->invoke_raw(mono_object, nullptr);

	return mono_object;
}

void CSharpInstance::mono_object_disposed(MonoObject *p_obj) {
	disconnect_event_signals();

#ifdef DEBUG_ENABLED
	CRASH_COND(base_ref);
	CRASH_COND(gchandle.is_released());
#endif
	CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);
}

void CSharpInstance::mono_object_disposed_baseref(MonoObject *p_obj, bool p_is_finalizer, bool &r_delete_owner, bool &r_remove_script_instance) {
#ifdef DEBUG_ENABLED
	CRASH_COND(!base_ref);
	CRASH_COND(gchandle.is_released());
#endif

	r_remove_script_instance = false;

	if (_unreference_owner_unsafe()) {
		// Safe to self destruct here with memdelete(owner), but it's deferred to the caller to prevent future mistakes.
		r_delete_owner = true;
	} else {
		r_delete_owner = false;
		CSharpLanguage::get_singleton()->release_script_gchandle(p_obj, gchandle);

		if (!p_is_finalizer) {
			// If the native instance is still alive and Dispose() was called
			// (instead of the finalizer), then we remove the script instance.
			r_remove_script_instance = true;
		} else if (!GDMono::get_singleton()->is_finalizing_scripts_domain()) {
			// If the native instance is still alive and this is called from the finalizer,
			// then it was referenced from another thread before the finalizer could
			// unreference and delete it, so we want to keep it.
			// GC.ReRegisterForFinalize(this) is not safe because the objects referenced by 'this'
			// could have already been collected. Instead we will create a new managed instance here.
			MonoObject *new_managed = _internal_new_managed();
			if (!new_managed) {
				r_remove_script_instance = true;
			}
		}
	}
}

void CSharpInstance::connect_event_signals() {
	for (const Map<StringName, CSharpScript::EventSignal>::Element *E = script->event_signals.front(); E; E = E->next()) {
		const CSharpScript::EventSignal &event_signal = E->value();

		StringName signal_name = event_signal.field->get_name();

		// TODO: Use pooling for ManagedCallable instances.
		auto event_signal_callable = memnew(EventSignalCallable(owner, &event_signal));

		owner->connect(signal_name, Callable(event_signal_callable));
	}
}

void CSharpInstance::disconnect_event_signals() {
	for (const Map<StringName, CSharpScript::EventSignal>::Element *E = script->event_signals.front(); E; E = E->next()) {
		const CSharpScript::EventSignal &event_signal = E->value();

		StringName signal_name = event_signal.field->get_name();

		// TODO: It would be great if we could store this EventSignalCallable on the stack.
		// The problem is that Callable memdeletes it when it's destructed...
		auto event_signal_callable = memnew(EventSignalCallable(owner, &event_signal));

		owner->disconnect(signal_name, Callable(event_signal_callable));
	}
}

void CSharpInstance::refcount_incremented() {
#ifdef DEBUG_ENABLED
	CRASH_COND(!base_ref);
	CRASH_COND(owner == nullptr);
#endif

	Reference *ref_owner = Object::cast_to<Reference>(owner);

	if (ref_owner->reference_get_count() > 1 && gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
		GD_MONO_SCOPE_THREAD_ATTACH;

		// The reference count was increased after the managed side was the only one referencing our owner.
		// This means the owner is being referenced again by the unmanaged side,
		// so the owner must hold the managed side alive again to avoid it from being GCed.

		// Release the current weak handle and replace it with a strong handle.
		MonoGCHandleData strong_gchandle = MonoGCHandleData::new_strong_handle(gchandle.get_target());
		gchandle.release();
		gchandle = strong_gchandle;
	}
}

bool CSharpInstance::refcount_decremented() {
#ifdef DEBUG_ENABLED
	CRASH_COND(!base_ref);
	CRASH_COND(owner == nullptr);
#endif

	Reference *ref_owner = Object::cast_to<Reference>(owner);

	int refcount = ref_owner->reference_get_count();

	if (refcount == 1 && !gchandle.is_weak()) { // The managed side also holds a reference, hence 1 instead of 0
		GD_MONO_SCOPE_THREAD_ATTACH;

		// If owner owner is no longer referenced by the unmanaged side,
		// the managed instance takes responsibility of deleting the owner when GCed.

		// Release the current strong handle and replace it with a weak handle.
		MonoGCHandleData weak_gchandle = MonoGCHandleData::new_weak_handle(gchandle.get_target());
		gchandle.release();
		gchandle = weak_gchandle;

		return false;
	}

	ref_dying = (refcount == 0);

	return ref_dying;
}

Vector<ScriptNetData> CSharpInstance::get_rpc_methods() const {
	return script->get_rpc_methods();
}

uint16_t CSharpInstance::get_rpc_method_id(const StringName &p_method) const {
	return script->get_rpc_method_id(p_method);
}

StringName CSharpInstance::get_rpc_method(const uint16_t p_rpc_method_id) const {
	return script->get_rpc_method(p_rpc_method_id);
}

MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const {
	return script->get_rpc_mode_by_id(p_rpc_method_id);
}

MultiplayerAPI::RPCMode CSharpInstance::get_rpc_mode(const StringName &p_method) const {
	return script->get_rpc_mode(p_method);
}

Vector<ScriptNetData> CSharpInstance::get_rset_properties() const {
	return script->get_rset_properties();
}

uint16_t CSharpInstance::get_rset_property_id(const StringName &p_variable) const {
	return script->get_rset_property_id(p_variable);
}

StringName CSharpInstance::get_rset_property(const uint16_t p_rset_member_id) const {
	return script->get_rset_property(p_rset_member_id);
}

MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode_by_id(const uint16_t p_rset_member_id) const {
	return script->get_rset_mode_by_id(p_rset_member_id);
}

MultiplayerAPI::RPCMode CSharpInstance::get_rset_mode(const StringName &p_variable) const {
	return script->get_rset_mode(p_variable);
}

void CSharpInstance::notification(int p_notification) {
	GD_MONO_SCOPE_THREAD_ATTACH;

	if (p_notification == Object::NOTIFICATION_PREDELETE) {
		// When NOTIFICATION_PREDELETE is sent, we also take the chance to call Dispose().
		// It's safe to call Dispose() multiple times and NOTIFICATION_PREDELETE is guaranteed
		// to be sent at least once, which happens right before the call to the destructor.

		predelete_notified = true;

		if (base_ref) {
			// It's not safe to proceed if the owner derives Reference and the refcount reached 0.
			// At this point, Dispose() was already called (manually or from the finalizer) so
			// that's not a problem. The refcount wouldn't have reached 0 otherwise, since the
			// managed side references it and Dispose() needs to be called to release it.
			// However, this means C# Reference scripts can't receive NOTIFICATION_PREDELETE, but
			// this is likely the case with GDScript as well: https://github.com/godotengine/godot/issues/6784
			return;
		}

		_call_notification(p_notification);

		MonoObject *mono_object = get_mono_object();
		ERR_FAIL_NULL(mono_object);

		MonoException *exc = nullptr;
		GDMonoUtils::dispose(mono_object, &exc);

		if (exc) {
			GDMonoUtils::set_pending_exception(exc);
		}

		return;
	}

	_call_notification(p_notification);
}

void CSharpInstance::_call_notification(int p_notification) {
	GD_MONO_ASSERT_THREAD_ATTACHED;

	MonoObject *mono_object = get_mono_object();
	ERR_FAIL_NULL(mono_object);

	// Custom version of _call_multilevel, optimized for _notification

	uint32_t arg = p_notification;
	void *args[1] = { &arg };
	StringName method_name = CACHED_STRING_NAME(_notification);

	GDMonoClass *top = script->script_class;

	while (top && top != script->native) {
		GDMonoMethod *method = top->get_method(method_name, 1);

		if (method) {
			method->invoke_raw(mono_object, args);
			return;
		}

		top = top->get_parent_class();
	}
}

String CSharpInstance::to_string(bool *r_valid) {
	GD_MONO_SCOPE_THREAD_ATTACH;

	MonoObject *mono_object = get_mono_object();

	if (mono_object == nullptr) {
		if (r_valid)
			*r_valid = false;
		return String();
	}

	MonoException *exc = nullptr;
	MonoString *result = GDMonoUtils::object_to_string(mono_object, &exc);

	if (exc) {
		GDMonoUtils::set_pending_exception(exc);
		if (r_valid)
			*r_valid = false;
		return String();
	}

	if (result == nullptr) {
		if (r_valid)
			*r_valid = false;
		return String();
	}

	return GDMonoMarshal::mono_string_to_godot(result);
}

Ref<Script> CSharpInstance::get_script() const {
	return script;
}

ScriptLanguage *CSharpInstance::get_language() {
	return CSharpLanguage::get_singleton();
}

CSharpInstance::CSharpInstance(const Ref<CSharpScript> &p_script) :
		script(p_script) {
}

CSharpInstance::~CSharpInstance() {
	GD_MONO_SCOPE_THREAD_ATTACH;

	destructing_script_instance = true;

	if (!gchandle.is_released()) {
		if (!predelete_notified && !ref_dying) {
			// This destructor is not called from the owners destructor.
			// This could be being called from the owner's set_script_instance method,
			// meaning this script is being replaced with another one. If this is the case,
			// we must call Dispose here, because Dispose calls owner->set_script_instance(nullptr)
			// and that would mess up with the new script instance if called later.

			MonoObject *mono_object = gchandle.get_target();

			if (mono_object) {
				MonoException *exc = nullptr;
				GDMonoUtils::dispose(mono_object, &exc);

				if (exc) {
					GDMonoUtils::set_pending_exception(exc);
				}
			}
		}

		gchandle.release(); // Make sure the gchandle is released
	}

	// If not being called from the owner's destructor, and we still hold a reference to the owner
	if (base_ref && !ref_dying && owner && unsafe_referenced) {
		// The owner's script or script instance is being replaced (or removed)

		// Transfer ownership to an "instance binding"

		Reference *ref_owner = static_cast<Reference *>(owner);

		// We will unreference the owner before referencing it again, so we need to keep it alive
		Ref<Reference> scope_keep_owner_alive(ref_owner);
		(void)scope_keep_owner_alive;

		// Unreference the owner here, before the new "instance binding" references it.
		// Otherwise, the unsafe reference debug checks will incorrectly detect a bug.
		bool die = _unreference_owner_unsafe();
		CRASH_COND(die == true); // `owner_keep_alive` holds a reference, so it can't die

		void *data = owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
		CRASH_COND(data == nullptr);

		CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();

		if (!script_binding.inited) {
			MutexLock lock(CSharpLanguage::get_singleton()->get_language_bind_mutex());

			if (!script_binding.inited) { // Other thread may have set it up
				// Already had a binding that needs to be setup
				CSharpLanguage::get_singleton()->setup_csharp_script_binding(script_binding, owner);
				CRASH_COND(!script_binding.inited);
			}
		}

#ifdef DEBUG_ENABLED
		// The "instance binding" holds a reference so the refcount should be at least 2 before `scope_keep_owner_alive` goes out of scope
		CRASH_COND(ref_owner->reference_get_count() <= 1);
#endif
	}

	if (script.is_valid() && owner) {
		MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);

#ifdef DEBUG_ENABLED
		// CSharpInstance must not be created unless it's going to be added to the list for sure
		Set<Object *>::Element *match = script->instances.find(owner);
		CRASH_COND(!match);
		script->instances.erase(match);
#else
		script->instances.erase(owner);
#endif
	}
}

#ifdef TOOLS_ENABLED
void CSharpScript::_placeholder_erased(PlaceHolderScriptInstance *p_placeholder) {
	placeholders.erase(p_placeholder);
}
#endif

#ifdef TOOLS_ENABLED
void CSharpScript::_update_exports_values(Map<StringName, Variant> &values, List<PropertyInfo> &propnames) {
	if (base_cache.is_valid()) {
		base_cache->_update_exports_values(values, propnames);
	}

	for (Map<StringName, Variant>::Element *E = exported_members_defval_cache.front(); E; E = E->next()) {
		values[E->key()] = E->get();
	}

	for (List<PropertyInfo>::Element *E = exported_members_cache.front(); E; E = E->next()) {
		propnames.push_back(E->get());
	}
}

void CSharpScript::_update_member_info_no_exports() {
	if (exports_invalidated) {
		GD_MONO_ASSERT_THREAD_ATTACHED;

		exports_invalidated = false;

		member_info.clear();

		GDMonoClass *top = script_class;

		while (top && top != native) {
			PropertyInfo prop_info;
			bool exported;

			const Vector<GDMonoField *> &fields = top->get_all_fields();

			for (int i = fields.size() - 1; i >= 0; i--) {
				GDMonoField *field = fields[i];

				if (_get_member_export(field, /* inspect export: */ false, prop_info, exported)) {
					StringName member_name = field->get_name();

					member_info[member_name] = prop_info;
					exported_members_cache.push_front(prop_info);
					exported_members_defval_cache[member_name] = Variant();
				}
			}

			const Vector<GDMonoProperty *> &properties = top->get_all_properties();

			for (int i = properties.size() - 1; i >= 0; i--) {
				GDMonoProperty *property = properties[i];

				if (_get_member_export(property, /* inspect export: */ false, prop_info, exported)) {
					StringName member_name = property->get_name();

					member_info[member_name] = prop_info;
					exported_members_cache.push_front(prop_info);
					exported_members_defval_cache[member_name] = Variant();
				}
			}

			top = top->get_parent_class();
		}
	}
}
#endif

bool CSharpScript::_update_exports() {
#ifdef TOOLS_ENABLED
	bool is_editor = Engine::get_singleton()->is_editor_hint();
	if (is_editor)
		placeholder_fallback_enabled = true; // until proven otherwise
#endif
	if (!valid)
		return false;

	bool changed = false;

#ifdef TOOLS_ENABLED
	if (exports_invalidated)
#endif
	{
		GD_MONO_SCOPE_THREAD_ATTACH;

		changed = true;

		member_info.clear();

#ifdef TOOLS_ENABLED
		MonoObject *tmp_object = nullptr;
		Object *tmp_native = nullptr;
		uint32_t tmp_pinned_gchandle = 0;

		if (is_editor) {
			exports_invalidated = false;

			exported_members_cache.clear();
			exported_members_defval_cache.clear();

			// Here we create a temporary managed instance of the class to get the initial values
			tmp_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());

			if (!tmp_object) {
				ERR_PRINT("Failed to allocate temporary MonoObject.");
				return false;
			}

			tmp_pinned_gchandle = GDMonoUtils::new_strong_gchandle_pinned(tmp_object); // pin it (not sure if needed)

			GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), 0);

			ERR_FAIL_NULL_V_MSG(ctor, false,
					"Cannot construct temporary MonoObject because the class does not define a parameterless constructor: '" + get_path() + "'.");

			MonoException *ctor_exc = nullptr;
			ctor->invoke(tmp_object, nullptr, &ctor_exc);

			tmp_native = GDMonoMarshal::unbox<Object *>(CACHED_FIELD(GodotObject, ptr)->get_value(tmp_object));

			if (ctor_exc) {
				// TODO: Should we free 'tmp_native' if the exception was thrown after its creation?

				GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
				tmp_object = nullptr;

				ERR_PRINT("Exception thrown from constructor of temporary MonoObject:");
				GDMonoUtils::debug_print_unhandled_exception(ctor_exc);
				return false;
			}
		}
#endif

		GDMonoClass *top = script_class;

		while (top && top != native) {
			PropertyInfo prop_info;
			bool exported;

			const Vector<GDMonoField *> &fields = top->get_all_fields();

			for (int i = fields.size() - 1; i >= 0; i--) {
				GDMonoField *field = fields[i];

				if (_get_member_export(field, /* inspect export: */ true, prop_info, exported)) {
					StringName member_name = field->get_name();

					member_info[member_name] = prop_info;

					if (exported) {
#ifdef TOOLS_ENABLED
						if (is_editor) {
							exported_members_cache.push_front(prop_info);

							if (tmp_object) {
								exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(field->get_value(tmp_object));
							}
						}
#endif

#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
						exported_members_names.insert(member_name);
#endif
					}
				}
			}

			const Vector<GDMonoProperty *> &properties = top->get_all_properties();

			for (int i = properties.size() - 1; i >= 0; i--) {
				GDMonoProperty *property = properties[i];

				if (_get_member_export(property, /* inspect export: */ true, prop_info, exported)) {
					StringName member_name = property->get_name();

					member_info[member_name] = prop_info;

					if (exported) {
#ifdef TOOLS_ENABLED
						if (is_editor) {
							exported_members_cache.push_front(prop_info);
							if (tmp_object) {
								MonoException *exc = nullptr;
								MonoObject *ret = property->get_value(tmp_object, &exc);
								if (exc) {
									exported_members_defval_cache[member_name] = Variant();
									GDMonoUtils::debug_print_unhandled_exception(exc);
								} else {
									exported_members_defval_cache[member_name] = GDMonoMarshal::mono_object_to_variant(ret);
								}
							}
						}
#endif

#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
						exported_members_names.insert(member_name);
#endif
					}
				}
			}

			top = top->get_parent_class();
		}

#ifdef TOOLS_ENABLED
		if (is_editor) {
			// Need to check this here, before disposal
			bool base_ref = Object::cast_to<Reference>(tmp_native) != nullptr;

			// Dispose the temporary managed instance

			MonoException *exc = nullptr;
			GDMonoUtils::dispose(tmp_object, &exc);

			if (exc) {
				ERR_PRINT("Exception thrown from method Dispose() of temporary MonoObject:");
				GDMonoUtils::debug_print_unhandled_exception(exc);
			}

			GDMonoUtils::free_gchandle(tmp_pinned_gchandle);
			tmp_object = nullptr;

			if (tmp_native && !base_ref) {
				Node *node = Object::cast_to<Node>(tmp_native);
				if (node && node->is_inside_tree()) {
					ERR_PRINT("Temporary instance was added to the scene tree.");
				} else {
					memdelete(tmp_native);
				}
			}
		}
#endif
	}

#ifdef TOOLS_ENABLED
	if (is_editor) {
		placeholder_fallback_enabled = false;

		if (placeholders.size()) {
			// Update placeholders if any
			Map<StringName, Variant> values;
			List<PropertyInfo> propnames;
			_update_exports_values(values, propnames);

			for (Set<PlaceHolderScriptInstance *>::Element *E = placeholders.front(); E; E = E->next()) {
				E->get()->update(propnames, values);
			}
		}
	}
#endif

	return changed;
}

void CSharpScript::load_script_signals(GDMonoClass *p_class, GDMonoClass *p_native_class) {
	// no need to load the script's signals more than once
	if (!signals_invalidated) {
		return;
	}

	// make sure this classes signals are empty when loading for the first time
	_signals.clear();
	event_signals.clear();

	GD_MONO_SCOPE_THREAD_ATTACH;

	GDMonoClass *top = p_class;
	while (top && top != p_native_class) {
		const Vector<GDMonoClass *> &delegates = top->get_all_delegates();
		for (int i = delegates.size() - 1; i >= 0; --i) {
			GDMonoClass *delegate = delegates[i];

			if (!delegate->has_attribute(CACHED_CLASS(SignalAttribute)))
				continue;

			// Arguments are accessibles as arguments of .Invoke method
			GDMonoMethod *invoke_method = delegate->get_method(mono_get_delegate_invoke(delegate->get_mono_ptr()));

			Vector<SignalParameter> parameters;
			if (_get_signal(top, invoke_method, parameters)) {
				_signals[delegate->get_name()] = parameters;
			}
		}

		List<StringName> found_event_signals;

		void *iter = nullptr;
		MonoEvent *raw_event = nullptr;
		while ((raw_event = mono_class_get_events(top->get_mono_ptr(), &iter)) != nullptr) {
			MonoCustomAttrInfo *event_attrs = mono_custom_attrs_from_event(top->get_mono_ptr(), raw_event);
			if (event_attrs) {
				if (mono_custom_attrs_has_attr(event_attrs, CACHED_CLASS(SignalAttribute)->get_mono_ptr())) {
					const char *event_name = mono_event_get_name(raw_event);
					found_event_signals.push_back(StringName(event_name));
				}

				mono_custom_attrs_free(event_attrs);
			}
		}

		const Vector<GDMonoField *> &fields = top->get_all_fields();
		for (int i = 0; i < fields.size(); i++) {
			GDMonoField *field = fields[i];

			GDMonoClass *field_class = field->get_type().type_class;

			if (!mono_class_is_delegate(field_class->get_mono_ptr()))
				continue;

			if (!found_event_signals.find(field->get_name()))
				continue;

			GDMonoMethod *invoke_method = field_class->get_method(mono_get_delegate_invoke(field_class->get_mono_ptr()));

			Vector<SignalParameter> parameters;
			if (_get_signal(top, invoke_method, parameters)) {
				event_signals[field->get_name()] = { field, invoke_method, parameters };
			}
		}

		top = top->get_parent_class();
	}

	signals_invalidated = false;
}

bool CSharpScript::_get_signal(GDMonoClass *p_class, GDMonoMethod *p_delegate_invoke, Vector<SignalParameter> &params) {
	GD_MONO_ASSERT_THREAD_ATTACHED;

	Vector<StringName> names;
	Vector<ManagedType> types;
	p_delegate_invoke->get_parameter_names(names);
	p_delegate_invoke->get_parameter_types(types);

	for (int i = 0; i < names.size(); ++i) {
		SignalParameter arg;
		arg.name = names[i];

		bool nil_is_variant = false;
		arg.type = GDMonoMarshal::managed_to_variant_type(types[i], &nil_is_variant);

		if (arg.type == Variant::NIL) {
			if (nil_is_variant) {
				arg.nil_is_variant = true;
			} else {
				ERR_PRINT("Unknown type of signal parameter: '" + arg.name + "' in '" + p_class->get_full_name() + "'.");
				return false;
			}
		}

		params.push_back(arg);
	}

	return true;
}

/**
 * Returns false if there was an error, otherwise true.
 * If there was an error, r_prop_info and r_exported are not assigned any value.
 */
bool CSharpScript::_get_member_export(IMonoClassMember *p_member, bool p_inspect_export, PropertyInfo &r_prop_info, bool &r_exported) {
	GD_MONO_ASSERT_THREAD_ATTACHED;

	// Goddammit, C++. All I wanted was some nested functions.
#define MEMBER_FULL_QUALIFIED_NAME(m_member) \
	(m_member->get_enclosing_class()->get_full_name() + "." + (String)m_member->get_name())

	if (p_member->is_static()) {
#ifdef TOOLS_ENABLED
		if (p_member->has_attribute(CACHED_CLASS(ExportAttribute)))
			ERR_PRINT("Cannot export member because it is static: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
#endif
		return false;
	}

	if (member_info.has(p_member->get_name()))
		return false;

	ManagedType type;

	if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_FIELD) {
		type = static_cast<GDMonoField *>(p_member)->get_type();
	} else if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
		type = static_cast<GDMonoProperty *>(p_member)->get_type();
	} else {
		CRASH_NOW();
	}

	bool exported = p_member->has_attribute(CACHED_CLASS(ExportAttribute));

	if (p_member->get_member_type() == IMonoClassMember::MEMBER_TYPE_PROPERTY) {
		GDMonoProperty *property = static_cast<GDMonoProperty *>(p_member);
		if (!property->has_getter()) {
#ifdef TOOLS_ENABLED
			if (exported)
				ERR_PRINT("Read-only property cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
#endif
			return false;
		}
		if (!property->has_setter()) {
#ifdef TOOLS_ENABLED
			if (exported)
				ERR_PRINT("Write-only property (without getter) cannot be exported: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
#endif
			return false;
		}
	}

	bool nil_is_variant = false;
	Variant::Type variant_type = GDMonoMarshal::managed_to_variant_type(type, &nil_is_variant);

	if (!p_inspect_export || !exported) {
		r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), PROPERTY_HINT_NONE, "", PROPERTY_USAGE_SCRIPT_VARIABLE);
		r_exported = false;
		return true;
	}

	MonoObject *attr = p_member->get_attribute(CACHED_CLASS(ExportAttribute));

	PropertyHint hint = PROPERTY_HINT_NONE;
	String hint_string;

	if (variant_type == Variant::NIL && !nil_is_variant) {
#ifdef TOOLS_ENABLED
		ERR_PRINT("Unknown exported member type: '" + MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");
#endif
		return false;
	}

#ifdef TOOLS_ENABLED
	int hint_res = _try_get_member_export_hint(p_member, type, variant_type, /* allow_generics: */ true, hint, hint_string);

	ERR_FAIL_COND_V_MSG(hint_res == -1, false,
			"Error while trying to determine information about the exported member: '" +
					MEMBER_FULL_QUALIFIED_NAME(p_member) + "'.");

	if (hint_res == 0) {
		hint = PropertyHint(CACHED_FIELD(ExportAttribute, hint)->get_int_value(attr));
		hint_string = CACHED_FIELD(ExportAttribute, hintString)->get_string_value(attr);
	}
#endif

	uint32_t prop_usage = PROPERTY_USAGE_DEFAULT | PROPERTY_USAGE_SCRIPT_VARIABLE;

	if (variant_type == Variant::NIL) {
		// System.Object (Variant)
		prop_usage |= PROPERTY_USAGE_NIL_IS_VARIANT;
	}

	r_prop_info = PropertyInfo(variant_type, (String)p_member->get_name(), hint, hint_string, prop_usage);
	r_exported = true;

	return true;

#undef MEMBER_FULL_QUALIFIED_NAME
}

#ifdef TOOLS_ENABLED
int CSharpScript::_try_get_member_export_hint(IMonoClassMember *p_member, ManagedType p_type, Variant::Type p_variant_type, bool p_allow_generics, PropertyHint &r_hint, String &r_hint_string) {
	if (p_variant_type == Variant::NIL) {
		// System.Object (Variant)
		return 1;
	}

	GD_MONO_ASSERT_THREAD_ATTACHED;

	if (p_variant_type == Variant::INT && p_type.type_encoding == MONO_TYPE_VALUETYPE && mono_class_is_enum(p_type.type_class->get_mono_ptr())) {
		r_hint = PROPERTY_HINT_ENUM;

		Vector<MonoClassField *> fields = p_type.type_class->get_enum_fields();

		MonoType *enum_basetype = mono_class_enum_basetype(p_type.type_class->get_mono_ptr());

		String name_only_hint_string;

		// True: enum Foo { Bar, Baz, Quux }
		// True: enum Foo { Bar = 0, Baz = 1, Quux = 2 }
		// False: enum Foo { Bar = 0, Baz = 7, Quux = 5 }
		bool uses_default_values = true;

		for (int i = 0; i < fields.size(); i++) {
			MonoClassField *field = fields[i];

			if (i > 0) {
				r_hint_string += ",";
				name_only_hint_string += ",";
			}

			String enum_field_name = mono_field_get_name(field);
			r_hint_string += enum_field_name;
			name_only_hint_string += enum_field_name;

			// TODO:
			// Instead of using mono_field_get_value_object, we can do this without boxing. Check the
			// internal mono functions: ves_icall_System_Enum_GetEnumValuesAndNames and the get_enum_field.

			MonoObject *val_obj = mono_field_get_value_object(mono_domain_get(), field, nullptr);

			ERR_FAIL_NULL_V_MSG(val_obj, -1, "Failed to get '" + enum_field_name + "' constant enum value.");

			bool r_error;
			uint64_t val = GDMonoUtils::unbox_enum_value(val_obj, enum_basetype, r_error);
			ERR_FAIL_COND_V_MSG(r_error, -1, "Failed to unbox '" + enum_field_name + "' constant enum value.");

			if (val != (unsigned int)i) {
				uses_default_values = false;
			}

			r_hint_string += ":";
			r_hint_string += String::num_uint64(val);
		}

		if (uses_default_values) {
			// If we use the format NAME:VAL, that's what the editor displays.
			// That's annoying if the user is not using custom values for the enum constants.
			// This may not be needed in the future if the editor is changed to not display values.
			r_hint_string = name_only_hint_string;
		}
	} else if (p_variant_type == Variant::OBJECT && CACHED_CLASS(GodotResource)->is_assignable_from(p_type.type_class)) {
		GDMonoClass *field_native_class = GDMonoUtils::get_class_native_base(p_type.type_class);
		CRASH_COND(field_native_class == nullptr);

		r_hint = PROPERTY_HINT_RESOURCE_TYPE;
		r_hint_string = String(NATIVE_GDMONOCLASS_NAME(field_native_class));
	} else if (p_allow_generics && p_variant_type == Variant::ARRAY) {
		// Nested arrays are not supported in the inspector

		ManagedType elem_type;

		if (!GDMonoMarshal::try_get_array_element_type(p_type, elem_type))
			return 0;

		Variant::Type elem_variant_type = GDMonoMarshal::managed_to_variant_type(elem_type);

		PropertyHint elem_hint = PROPERTY_HINT_NONE;
		String elem_hint_string;

		ERR_FAIL_COND_V_MSG(elem_variant_type == Variant::NIL, -1, "Unknown array element type.");

		int hint_res = _try_get_member_export_hint(p_member, elem_type, elem_variant_type, /* allow_generics: */ false, elem_hint, elem_hint_string);

		ERR_FAIL_COND_V_MSG(hint_res == -1, -1, "Error while trying to determine information about the array element type.");

		// Format: type/hint:hint_string
		r_hint_string = itos(elem_variant_type) + "/" + itos(elem_hint) + ":" + elem_hint_string;
		r_hint = PROPERTY_HINT_TYPE_STRING;

	} else if (p_allow_generics && p_variant_type == Variant::DICTIONARY) {
		// TODO: Dictionaries are not supported in the inspector
	} else {
		return 0;
	}

	return 1;
}
#endif

void CSharpScript::_clear() {
	tool = false;
	valid = false;

	base = nullptr;
	native = nullptr;
	script_class = nullptr;
}

Variant CSharpScript::call(const StringName &p_method, const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
	if (unlikely(GDMono::get_singleton() == nullptr)) {
		// Probably not the best error but eh.
		r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
		return Variant();
	}

	GD_MONO_SCOPE_THREAD_ATTACH;

	GDMonoClass *top = script_class;

	while (top && top != native) {
		GDMonoMethod *method = top->get_method(p_method, p_argcount);

		if (method && method->is_static()) {
			MonoObject *result = method->invoke(nullptr, p_args);

			if (result) {
				return GDMonoMarshal::mono_object_to_variant(result);
			} else {
				return Variant();
			}
		}

		top = top->get_parent_class();
	}

	// No static method found. Try regular instance calls
	return Script::call(p_method, p_args, p_argcount, r_error);
}

void CSharpScript::_resource_path_changed() {
	String path = get_path();

	if (!path.empty()) {
		name = get_path().get_file().get_basename();
	}
}

bool CSharpScript::_get(const StringName &p_name, Variant &r_ret) const {
	if (p_name == CSharpLanguage::singleton->string_names._script_source) {
		r_ret = get_source_code();
		return true;
	}

	return false;
}

bool CSharpScript::_set(const StringName &p_name, const Variant &p_value) {
	if (p_name == CSharpLanguage::singleton->string_names._script_source) {
		set_source_code(p_value);
		reload();
		return true;
	}

	return false;
}

void CSharpScript::_get_property_list(List<PropertyInfo> *p_properties) const {
	p_properties->push_back(PropertyInfo(Variant::STRING, CSharpLanguage::singleton->string_names._script_source, PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR | PROPERTY_USAGE_INTERNAL));
}

void CSharpScript::_bind_methods() {
	ClassDB::bind_vararg_method(METHOD_FLAGS_DEFAULT, "new", &CSharpScript::_new, MethodInfo("new"));
}

Ref<CSharpScript> CSharpScript::create_for_managed_type(GDMonoClass *p_class, GDMonoClass *p_native) {
	// This method should not fail, only assertions allowed

	CRASH_COND(p_class == nullptr);

	// TODO OPTIMIZE: Cache the 'CSharpScript' associated with this 'p_class' instead of allocating a new one every time
	Ref<CSharpScript> script = memnew(CSharpScript);

	initialize_for_managed_type(script, p_class, p_native);

	return script;
}

void CSharpScript::initialize_for_managed_type(Ref<CSharpScript> p_script, GDMonoClass *p_class, GDMonoClass *p_native) {
	// This method should not fail, only assertions allowed

	CRASH_COND(p_class == nullptr);

	p_script->name = p_class->get_name();
	p_script->script_class = p_class;
	p_script->native = p_native;

	CRASH_COND(p_script->native == nullptr);

	GDMonoClass *base = p_script->script_class->get_parent_class();

	if (base != p_script->native)
		p_script->base = base;

	p_script->valid = true;
	p_script->tool = p_script->script_class->has_attribute(CACHED_CLASS(ToolAttribute));

	if (!p_script->tool) {
		GDMonoClass *nesting_class = p_script->script_class->get_nesting_class();
		p_script->tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
	}

#if TOOLS_ENABLED
	if (!p_script->tool) {
		p_script->tool = p_script->script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
	}
#endif

#ifdef DEBUG_ENABLED
	// For debug builds, we must fetch from all native base methods as well.
	// Native base methods must be fetched before the current class.
	// Not needed if the script class itself is a native class.

	if (p_script->script_class != p_script->native) {
		GDMonoClass *native_top = p_script->native;
		while (native_top) {
			native_top->fetch_methods_with_godot_api_checks(p_script->native);

			if (native_top == CACHED_CLASS(GodotObject))
				break;

			native_top = native_top->get_parent_class();
		}
	}
#endif

	p_script->script_class->fetch_methods_with_godot_api_checks(p_script->native);

	// Need to fetch method from base classes as well
	GDMonoClass *top = p_script->script_class;
	while (top && top != p_script->native) {
		top->fetch_methods_with_godot_api_checks(p_script->native);
		top = top->get_parent_class();
	}

	p_script->load_script_signals(p_script->script_class, p_script->native);
#ifdef TOOLS_ENABLED
	p_script->_update_member_info_no_exports();
#endif
}

bool CSharpScript::can_instance() const {
#ifdef TOOLS_ENABLED
	bool extra_cond = tool || ScriptServer::is_scripting_enabled();
#else
	bool extra_cond = true;
#endif

	// FIXME Need to think this through better.
	// For tool scripts, this will never fire if the class is not found. That's because we
	// don't know if it's a tool script if we can't find the class to access the attributes.
	if (extra_cond && !script_class) {
		if (GDMono::get_singleton()->get_project_assembly() == nullptr) {
			// The project assembly is not loaded
			ERR_FAIL_V_MSG(false, "Cannot instance script because the project assembly is not loaded. Script: '" + get_path() + "'.");
		} else {
			// The project assembly is loaded, but the class could not found
			ERR_FAIL_V_MSG(false, "Cannot instance script because the class '" + name + "' could not be found. Script: '" + get_path() + "'.");
		}
	}

	return valid && extra_cond;
}

StringName CSharpScript::get_instance_base_type() const {
	if (native)
		return native->get_name();
	else
		return StringName();
}

CSharpInstance *CSharpScript::_create_instance(const Variant **p_args, int p_argcount, Object *p_owner, bool p_isref, Callable::CallError &r_error) {
	GD_MONO_ASSERT_THREAD_ATTACHED;

	/* STEP 1, CREATE */

	// Search the constructor first, to fail with an error if it's not found before allocating anything else.
	GDMonoMethod *ctor = script_class->get_method(CACHED_STRING_NAME(dotctor), p_argcount);
	if (ctor == nullptr) {
		ERR_FAIL_COND_V_MSG(p_argcount == 0, nullptr,
				"Cannot create script instance. The class '" + script_class->get_full_name() +
						"' does not define a parameterless constructor." +
						(get_path().empty() ? String() : " Path: '" + get_path() + "'."));

		ERR_FAIL_V_MSG(nullptr, "Constructor not found.");
	}

	Ref<Reference> ref;
	if (p_isref) {
		// Hold it alive. Important if we have to dispose a script instance binding before creating the CSharpInstance.
		ref = Ref<Reference>(static_cast<Reference *>(p_owner));
	}

	// If the object had a script instance binding, dispose it before adding the CSharpInstance
	if (p_owner->has_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index())) {
		void *data = p_owner->get_script_instance_binding(CSharpLanguage::get_singleton()->get_language_index());
		CRASH_COND(data == nullptr);

		CSharpScriptBinding &script_binding = ((Map<Object *, CSharpScriptBinding>::Element *)data)->get();
		if (script_binding.inited && !script_binding.gchandle.is_released()) {
			MonoObject *mono_object = script_binding.gchandle.get_target();
			if (mono_object) {
				MonoException *exc = nullptr;
				GDMonoUtils::dispose(mono_object, &exc);

				if (exc) {
					GDMonoUtils::set_pending_exception(exc);
				}
			}

			script_binding.gchandle.release(); // Just in case
			script_binding.inited = false;
		}
	}

	CSharpInstance *instance = memnew(CSharpInstance(Ref<CSharpScript>(this)));
	instance->base_ref = p_isref;
	instance->owner = p_owner;
	instance->owner->set_script_instance(instance);

	/* STEP 2, INITIALIZE AND CONSTRUCT */

	MonoObject *mono_object = mono_object_new(mono_domain_get(), script_class->get_mono_ptr());

	if (!mono_object) {
		// Important to clear this before destroying the script instance here
		instance->script = Ref<CSharpScript>();
		instance->owner = nullptr;

		bool die = instance->_unreference_owner_unsafe();
		// Not ok for the owner to die here. If there is a situation where this can happen, it will be considered a bug.
		CRASH_COND(die == true);

		p_owner->set_script_instance(nullptr);
		r_error.error = Callable::CallError::CALL_ERROR_INSTANCE_IS_NULL;
		ERR_FAIL_V_MSG(nullptr, "Failed to allocate memory for the object.");
	}

	// Tie managed to unmanaged
	instance->gchandle = MonoGCHandleData::new_strong_handle(mono_object);

	if (instance->base_ref)
		instance->_reference_owner_unsafe(); // Here, after assigning the gchandle (for the refcount_incremented callback)

	{
		MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
		instances.insert(instance->owner);
	}

	CACHED_FIELD(GodotObject, ptr)->set_value_raw(mono_object, instance->owner);

	// Construct
	ctor->invoke(mono_object, p_args);

	/* STEP 3, PARTY */

	//@TODO make thread safe
	return instance;
}

Variant CSharpScript::_new(const Variant **p_args, int p_argcount, Callable::CallError &r_error) {
	if (!valid) {
		r_error.error = Callable::CallError::CALL_ERROR_INVALID_METHOD;
		return Variant();
	}

	r_error.error = Callable::CallError::CALL_OK;

	ERR_FAIL_NULL_V(native, Variant());

	GD_MONO_SCOPE_THREAD_ATTACH;

	Object *owner = ClassDB::instance(NATIVE_GDMONOCLASS_NAME(native));

	REF ref;
	Reference *r = Object::cast_to<Reference>(owner);
	if (r) {
		ref = REF(r);
	}

	CSharpInstance *instance = _create_instance(p_args, p_argcount, owner, r != nullptr, r_error);
	if (!instance) {
		if (ref.is_null()) {
			memdelete(owner); //no owner, sorry
		}
		return Variant();
	}

	if (ref.is_valid()) {
		return ref;
	} else {
		return owner;
	}
}

ScriptInstance *CSharpScript::instance_create(Object *p_this) {
#ifdef DEBUG_ENABLED
	CRASH_COND(!valid);
#endif

	if (native) {
		StringName native_name = NATIVE_GDMONOCLASS_NAME(native);
		if (!ClassDB::is_parent_class(p_this->get_class_name(), native_name)) {
			if (EngineDebugger::is_active()) {
				CSharpLanguage::get_singleton()->debug_break_parse(get_path(), 0,
						"Script inherits from native type '" + String(native_name) +
								"', so it can't be instanced in object of type: '" + p_this->get_class() + "'");
			}
			ERR_FAIL_V_MSG(nullptr, "Script inherits from native type '" + String(native_name) +
											"', so it can't be instanced in object of type: '" + p_this->get_class() + "'.");
		}
	}

	GD_MONO_SCOPE_THREAD_ATTACH;

	Callable::CallError unchecked_error;
	return _create_instance(nullptr, 0, p_this, Object::cast_to<Reference>(p_this) != nullptr, unchecked_error);
}

PlaceHolderScriptInstance *CSharpScript::placeholder_instance_create(Object *p_this) {
#ifdef TOOLS_ENABLED
	PlaceHolderScriptInstance *si = memnew(PlaceHolderScriptInstance(CSharpLanguage::get_singleton(), Ref<Script>(this), p_this));
	placeholders.insert(si);
	_update_exports();
	return si;
#else
	return nullptr;
#endif
}

bool CSharpScript::instance_has(const Object *p_this) const {
	MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
	return instances.has((Object *)p_this);
}

bool CSharpScript::has_source_code() const {
	return !source.empty();
}

String CSharpScript::get_source_code() const {
	return source;
}

void CSharpScript::set_source_code(const String &p_code) {
	if (source == p_code)
		return;
	source = p_code;
#ifdef TOOLS_ENABLED
	source_changed_cache = true;
#endif
}

void CSharpScript::get_script_method_list(List<MethodInfo> *p_list) const {
	if (!script_class)
		return;

	GD_MONO_SCOPE_THREAD_ATTACH;

	// TODO: Filter out things unsuitable for explicit calls, like constructors.
	const Vector<GDMonoMethod *> &methods = script_class->get_all_methods();
	for (int i = 0; i < methods.size(); ++i) {
		p_list->push_back(methods[i]->get_method_info());
	}
}

bool CSharpScript::has_method(const StringName &p_method) const {
	if (!script_class)
		return false;

	GD_MONO_SCOPE_THREAD_ATTACH;

	return script_class->has_fetched_method_unknown_params(p_method);
}

MethodInfo CSharpScript::get_method_info(const StringName &p_method) const {
	if (!script_class)
		return MethodInfo();

	GD_MONO_SCOPE_THREAD_ATTACH;

	GDMonoClass *top = script_class;

	while (top && top != native) {
		GDMonoMethod *params = top->get_fetched_method_unknown_params(p_method);
		if (params) {
			return params->get_method_info();
		}

		top = top->get_parent_class();
	}

	return MethodInfo();
}

Error CSharpScript::reload(bool p_keep_state) {
	bool has_instances;
	{
		MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
		has_instances = instances.size();
	}

	ERR_FAIL_COND_V(!p_keep_state && has_instances, ERR_ALREADY_IN_USE);

	GD_MONO_SCOPE_THREAD_ATTACH;

	GDMonoAssembly *project_assembly = GDMono::get_singleton()->get_project_assembly();

	if (project_assembly) {
		const Variant *script_metadata_var = CSharpLanguage::get_singleton()->get_scripts_metadata().getptr(get_path());
		if (script_metadata_var) {
			Dictionary script_metadata = script_metadata_var->operator Dictionary()["class"];
			const Variant *namespace_ = script_metadata.getptr("namespace");
			const Variant *class_name = script_metadata.getptr("class_name");
			ERR_FAIL_NULL_V(namespace_, ERR_BUG);
			ERR_FAIL_NULL_V(class_name, ERR_BUG);
			GDMonoClass *klass = project_assembly->get_class(namespace_->operator String(), class_name->operator String());
			if (klass && CACHED_CLASS(GodotObject)->is_assignable_from(klass)) {
				script_class = klass;
			}
		} else {
			// Missing script metadata. Fallback to legacy method
			script_class = project_assembly->get_object_derived_class(name);
		}

		valid = script_class != nullptr;

		if (script_class) {
#ifdef DEBUG_ENABLED
			print_verbose("Found class " + script_class->get_full_name() + " for script " + get_path());
#endif

			tool = script_class->has_attribute(CACHED_CLASS(ToolAttribute));

			if (!tool) {
				GDMonoClass *nesting_class = script_class->get_nesting_class();
				tool = nesting_class && nesting_class->has_attribute(CACHED_CLASS(ToolAttribute));
			}

#if TOOLS_ENABLED
			if (!tool) {
				tool = script_class->get_assembly() == GDMono::get_singleton()->get_tools_assembly();
			}
#endif

			native = GDMonoUtils::get_class_native_base(script_class);

			CRASH_COND(native == nullptr);

			GDMonoClass *base_class = script_class->get_parent_class();

			if (base_class != native)
				base = base_class;

#ifdef DEBUG_ENABLED
			// For debug builds, we must fetch from all native base methods as well.
			// Native base methods must be fetched before the current class.
			// Not needed if the script class itself is a native class.

			if (script_class != native) {
				GDMonoClass *native_top = native;
				while (native_top) {
					native_top->fetch_methods_with_godot_api_checks(native);

					if (native_top == CACHED_CLASS(GodotObject))
						break;

					native_top = native_top->get_parent_class();
				}
			}
#endif

			script_class->fetch_methods_with_godot_api_checks(native);

			// Need to fetch method from base classes as well
			GDMonoClass *top = script_class;
			while (top && top != native) {
				top->fetch_methods_with_godot_api_checks(native);
				top = top->get_parent_class();
			}

			load_script_signals(script_class, native);
			_update_exports();
		}

		rpc_functions.clear();
		rpc_variables.clear();

		GDMonoClass *top = script_class;
		while (top && top != native) {
			{
				Vector<GDMonoMethod *> methods = top->get_all_methods();
				for (int i = 0; i < methods.size(); i++) {
					if (!methods[i]->is_static()) {
						MultiplayerAPI::RPCMode mode = _member_get_rpc_mode(methods[i]);
						if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
							ScriptNetData nd;
							nd.name = methods[i]->get_name();
							nd.mode = mode;
							if (-1 == rpc_functions.find(nd)) {
								rpc_functions.push_back(nd);
							}
						}
					}
				}
			}

			{
				Vector<GDMonoField *> fields = top->get_all_fields();
				for (int i = 0; i < fields.size(); i++) {
					if (!fields[i]->is_static()) {
						MultiplayerAPI::RPCMode mode = _member_get_rpc_mode(fields[i]);
						if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
							ScriptNetData nd;
							nd.name = fields[i]->get_name();
							nd.mode = mode;
							if (-1 == rpc_variables.find(nd)) {
								rpc_variables.push_back(nd);
							}
						}
					}
				}
			}

			{
				Vector<GDMonoProperty *> properties = top->get_all_properties();
				for (int i = 0; i < properties.size(); i++) {
					if (!properties[i]->is_static()) {
						MultiplayerAPI::RPCMode mode = _member_get_rpc_mode(properties[i]);
						if (MultiplayerAPI::RPC_MODE_DISABLED != mode) {
							ScriptNetData nd;
							nd.name = properties[i]->get_name();
							nd.mode = mode;
							if (-1 == rpc_variables.find(nd)) {
								rpc_variables.push_back(nd);
							}
						}
					}
				}
			}

			top = top->get_parent_class();
		}

		// Sort so we are 100% that they are always the same.
		rpc_functions.sort_custom<SortNetData>();
		rpc_variables.sort_custom<SortNetData>();

		return OK;
	}

	return ERR_FILE_MISSING_DEPENDENCIES;
}

ScriptLanguage *CSharpScript::get_language() const {
	return CSharpLanguage::get_singleton();
}

bool CSharpScript::get_property_default_value(const StringName &p_property, Variant &r_value) const {
#ifdef TOOLS_ENABLED

	const Map<StringName, Variant>::Element *E = exported_members_defval_cache.find(p_property);
	if (E) {
		r_value = E->get();
		return true;
	}

	if (base_cache.is_valid()) {
		return base_cache->get_property_default_value(p_property, r_value);
	}

#endif
	return false;
}

void CSharpScript::update_exports() {
#ifdef TOOLS_ENABLED
	_update_exports();
#endif
}

bool CSharpScript::has_script_signal(const StringName &p_signal) const {
	return event_signals.has(p_signal) || _signals.has(p_signal);
}

void CSharpScript::get_script_signal_list(List<MethodInfo> *r_signals) const {
	for (const Map<StringName, Vector<SignalParameter>>::Element *E = _signals.front(); E; E = E->next()) {
		MethodInfo mi;
		mi.name = E->key();

		const Vector<SignalParameter> &params = E->value();
		for (int i = 0; i < params.size(); i++) {
			const SignalParameter &param = params[i];

			PropertyInfo arg_info = PropertyInfo(param.type, param.name);
			if (param.type == Variant::NIL && param.nil_is_variant)
				arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;

			mi.arguments.push_back(arg_info);
		}

		r_signals->push_back(mi);
	}

	for (const Map<StringName, EventSignal>::Element *E = event_signals.front(); E; E = E->next()) {
		MethodInfo mi;
		mi.name = E->key();

		const EventSignal &event_signal = E->value();
		const Vector<SignalParameter> &params = event_signal.parameters;
		for (int i = 0; i < params.size(); i++) {
			const SignalParameter &param = params[i];

			PropertyInfo arg_info = PropertyInfo(param.type, param.name);
			if (param.type == Variant::NIL && param.nil_is_variant)
				arg_info.usage |= PROPERTY_USAGE_NIL_IS_VARIANT;

			mi.arguments.push_back(arg_info);
		}

		r_signals->push_back(mi);
	}
}

bool CSharpScript::inherits_script(const Ref<Script> &p_script) const {
	Ref<CSharpScript> cs = p_script;
	if (cs.is_null()) {
		return false;
	}

	if (script_class == nullptr || cs->script_class == nullptr) {
		return false;
	}

	if (script_class == cs->script_class) {
		return true;
	}

	return cs->script_class->is_assignable_from(script_class);
}

Ref<Script> CSharpScript::get_base_script() const {
	// TODO search in metadata file once we have it, not important any way?
	return Ref<Script>();
}

void CSharpScript::get_script_property_list(List<PropertyInfo> *p_list) const {
	for (Map<StringName, PropertyInfo>::Element *E = member_info.front(); E; E = E->next()) {
		p_list->push_back(E->value());
	}
}

int CSharpScript::get_member_line(const StringName &p_member) const {
	// TODO omnisharp
	return -1;
}

MultiplayerAPI::RPCMode CSharpScript::_member_get_rpc_mode(IMonoClassMember *p_member) const {
	if (p_member->has_attribute(CACHED_CLASS(RemoteAttribute)))
		return MultiplayerAPI::RPC_MODE_REMOTE;
	if (p_member->has_attribute(CACHED_CLASS(MasterAttribute)))
		return MultiplayerAPI::RPC_MODE_MASTER;
	if (p_member->has_attribute(CACHED_CLASS(PuppetAttribute)))
		return MultiplayerAPI::RPC_MODE_PUPPET;
	if (p_member->has_attribute(CACHED_CLASS(RemoteSyncAttribute)))
		return MultiplayerAPI::RPC_MODE_REMOTESYNC;
	if (p_member->has_attribute(CACHED_CLASS(MasterSyncAttribute)))
		return MultiplayerAPI::RPC_MODE_MASTERSYNC;
	if (p_member->has_attribute(CACHED_CLASS(PuppetSyncAttribute)))
		return MultiplayerAPI::RPC_MODE_PUPPETSYNC;

	return MultiplayerAPI::RPC_MODE_DISABLED;
}

Vector<ScriptNetData> CSharpScript::get_rpc_methods() const {
	return rpc_functions;
}

uint16_t CSharpScript::get_rpc_method_id(const StringName &p_method) const {
	for (int i = 0; i < rpc_functions.size(); i++) {
		if (rpc_functions[i].name == p_method) {
			return i;
		}
	}
	return UINT16_MAX;
}

StringName CSharpScript::get_rpc_method(const uint16_t p_rpc_method_id) const {
	ERR_FAIL_COND_V(p_rpc_method_id >= rpc_functions.size(), StringName());
	return rpc_functions[p_rpc_method_id].name;
}

MultiplayerAPI::RPCMode CSharpScript::get_rpc_mode_by_id(const uint16_t p_rpc_method_id) const {
	ERR_FAIL_COND_V(p_rpc_method_id >= rpc_functions.size(), MultiplayerAPI::RPC_MODE_DISABLED);
	return rpc_functions[p_rpc_method_id].mode;
}

MultiplayerAPI::RPCMode CSharpScript::get_rpc_mode(const StringName &p_method) const {
	return get_rpc_mode_by_id(get_rpc_method_id(p_method));
}

Vector<ScriptNetData> CSharpScript::get_rset_properties() const {
	return rpc_variables;
}

uint16_t CSharpScript::get_rset_property_id(const StringName &p_variable) const {
	for (int i = 0; i < rpc_variables.size(); i++) {
		if (rpc_variables[i].name == p_variable) {
			return i;
		}
	}
	return UINT16_MAX;
}

StringName CSharpScript::get_rset_property(const uint16_t p_rset_member_id) const {
	ERR_FAIL_COND_V(p_rset_member_id >= rpc_variables.size(), StringName());
	return rpc_variables[p_rset_member_id].name;
}

MultiplayerAPI::RPCMode CSharpScript::get_rset_mode_by_id(const uint16_t p_rset_member_id) const {
	ERR_FAIL_COND_V(p_rset_member_id >= rpc_functions.size(), MultiplayerAPI::RPC_MODE_DISABLED);
	return rpc_functions[p_rset_member_id].mode;
}

MultiplayerAPI::RPCMode CSharpScript::get_rset_mode(const StringName &p_variable) const {
	return get_rset_mode_by_id(get_rset_property_id(p_variable));
}

Error CSharpScript::load_source_code(const String &p_path) {
	Error ferr = read_all_file_utf8(p_path, source);

	ERR_FAIL_COND_V_MSG(ferr != OK, ferr,
			ferr == ERR_INVALID_DATA ?
					"Script '" + p_path + "' contains invalid unicode (UTF-8), so it was not loaded."
										  " Please ensure that scripts are saved in valid UTF-8 unicode." :
					"Failed to read file: '" + p_path + "'.");

#ifdef TOOLS_ENABLED
	source_changed_cache = true;
#endif

	return OK;
}

StringName CSharpScript::get_script_name() const {
	return name;
}

CSharpScript::CSharpScript() {
	_clear();

	_resource_path_changed();

#ifdef DEBUG_ENABLED
	{
		MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
		CSharpLanguage::get_singleton()->script_list.add(&this->script_list);
	}
#endif
}

CSharpScript::~CSharpScript() {
#ifdef DEBUG_ENABLED
	MutexLock lock(CSharpLanguage::get_singleton()->script_instances_mutex);
	CSharpLanguage::get_singleton()->script_list.remove(&this->script_list);
#endif
}

void CSharpScript::get_members(Set<StringName> *p_members) {
#if defined(TOOLS_ENABLED) || defined(DEBUG_ENABLED)
	if (p_members) {
		for (Set<StringName>::Element *E = exported_members_names.front(); E; E = E->next()) {
			p_members->insert(E->get());
		}
	}
#endif
}

/*************** RESOURCE ***************/

RES ResourceFormatLoaderCSharpScript::load(const String &p_path, const String &p_original_path, Error *r_error, bool p_use_sub_threads, float *r_progress, bool p_no_cache) {
	if (r_error)
		*r_error = ERR_FILE_CANT_OPEN;

	// TODO ignore anything inside bin/ and obj/ in tools builds?

	CSharpScript *script = memnew(CSharpScript);

	Ref<CSharpScript> scriptres(script);

#if defined(DEBUG_ENABLED) || defined(TOOLS_ENABLED)
	Error err = script->load_source_code(p_path);
	ERR_FAIL_COND_V_MSG(err != OK, RES(), "Cannot load C# script file '" + p_path + "'.");
#endif

	script->set_path(p_original_path);

	script->reload();

	if (r_error)
		*r_error = OK;

	return scriptres;
}

void ResourceFormatLoaderCSharpScript::get_recognized_extensions(List<String> *p_extensions) const {
	p_extensions->push_back("cs");
}

bool ResourceFormatLoaderCSharpScript::handles_type(const String &p_type) const {
	return p_type == "Script" || p_type == CSharpLanguage::get_singleton()->get_type();
}

String ResourceFormatLoaderCSharpScript::get_resource_type(const String &p_path) const {
	return p_path.get_extension().to_lower() == "cs" ? CSharpLanguage::get_singleton()->get_type() : "";
}

Error ResourceFormatSaverCSharpScript::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {
	Ref<CSharpScript> sqscr = p_resource;
	ERR_FAIL_COND_V(sqscr.is_null(), ERR_INVALID_PARAMETER);

	String source = sqscr->get_source_code();

#ifdef TOOLS_ENABLED
	if (!FileAccess::exists(p_path)) {
		// The file does not yet exists, let's assume the user just created this script

		if (_create_project_solution_if_needed()) {
			CSharpProject::add_item(GodotSharpDirs::get_project_csproj_path(),
					"Compile",
					ProjectSettings::get_singleton()->globalize_path(p_path));
		} else {
			ERR_PRINT("C# project could not be created; cannot add file: '" + p_path + "'.");
		}
	}
#endif

	Error err;
	FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);
	ERR_FAIL_COND_V_MSG(err != OK, err, "Cannot save C# script file '" + p_path + "'.");

	file->store_string(source);

	if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
		memdelete(file);
		return ERR_CANT_CREATE;
	}

	file->close();
	memdelete(file);

#ifdef TOOLS_ENABLED
	if (ScriptServer::is_reload_scripts_on_save_enabled()) {
		CSharpLanguage::get_singleton()->reload_tool_script(p_resource, false);
	}
#endif

	return OK;
}

void ResourceFormatSaverCSharpScript::get_recognized_extensions(const RES &p_resource, List<String> *p_extensions) const {
	if (Object::cast_to<CSharpScript>(p_resource.ptr())) {
		p_extensions->push_back("cs");
	}
}

bool ResourceFormatSaverCSharpScript::recognize(const RES &p_resource) const {
	return Object::cast_to<CSharpScript>(p_resource.ptr()) != nullptr;
}

CSharpLanguage::StringNameCache::StringNameCache() {
	_signal_callback = StaticCString::create("_signal_callback");
	_set = StaticCString::create("_set");
	_get = StaticCString::create("_get");
	_get_property_list = StaticCString::create("_get_property_list");
	_notification = StaticCString::create("_notification");
	_script_source = StaticCString::create("script/source");
	on_before_serialize = StaticCString::create("OnBeforeSerialize");
	on_after_deserialize = StaticCString::create("OnAfterDeserialize");
	dotctor = StaticCString::create(".ctor");
	delegate_invoke_method_name = StaticCString::create("Invoke");
}