1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
|
/**
* Defines a function declaration.
*
* Includes:
* - function/delegate literals
* - function aliases
* - (static/shared) constructors/destructors/post-blits
* - `invariant`
* - `unittest`
*
* Copyright: Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/func.d, _func.d)
* Documentation: https://dlang.org/phobos/dmd_func.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/func.d
*/
module dmd.func;
import core.stdc.stdio;
import core.stdc.string;
import dmd.aggregate;
import dmd.arraytypes;
import dmd.astenums;
import dmd.blockexit;
import dmd.gluelayer;
import dmd.dclass;
import dmd.declaration;
import dmd.delegatize;
import dmd.dinterpret;
import dmd.dmodule;
import dmd.dscope;
import dmd.dstruct;
import dmd.dsymbol;
import dmd.dsymbolsem;
import dmd.dtemplate;
import dmd.errors;
import dmd.escape;
import dmd.expression;
import dmd.globals;
import dmd.hdrgen;
import dmd.id;
import dmd.identifier;
import dmd.init;
import dmd.mtype;
import dmd.objc;
import dmd.root.aav;
import dmd.common.outbuffer;
import dmd.root.rootobject;
import dmd.root.string;
import dmd.root.stringtable;
import dmd.semantic2;
import dmd.semantic3;
import dmd.statement_rewrite_walker;
import dmd.statement;
import dmd.statementsem;
import dmd.tokens;
import dmd.visitor;
/// Inline Status
enum ILS : ubyte
{
uninitialized, /// not computed yet
no, /// cannot inline
yes, /// can inline
}
enum BUILTIN : ubyte
{
unknown = 255, /// not known if this is a builtin
unimp = 0, /// this is not a builtin
gcc, /// this is a GCC builtin
llvm, /// this is an LLVM builtin
sin,
cos,
tan,
sqrt,
fabs,
ldexp,
log,
log2,
log10,
exp,
expm1,
exp2,
round,
floor,
ceil,
trunc,
copysign,
pow,
fmin,
fmax,
fma,
isnan,
isinfinity,
isfinite,
bsf,
bsr,
bswap,
popcnt,
yl2x,
yl2xp1,
toPrecFloat,
toPrecDouble,
toPrecReal
}
/* Tweak all return statements and dtor call for nrvo_var, for correct NRVO.
*/
extern (C++) final class NrvoWalker : StatementRewriteWalker
{
alias visit = typeof(super).visit;
public:
FuncDeclaration fd;
Scope* sc;
override void visit(ReturnStatement s)
{
// See if all returns are instead to be replaced with a goto returnLabel;
if (fd.returnLabel)
{
/* Rewrite:
* return exp;
* as:
* vresult = exp; goto Lresult;
*/
auto gs = new GotoStatement(s.loc, Id.returnLabel);
gs.label = fd.returnLabel;
Statement s1 = gs;
if (s.exp)
s1 = new CompoundStatement(s.loc, new ExpStatement(s.loc, s.exp), gs);
replaceCurrent(s1);
}
}
override void visit(TryFinallyStatement s)
{
DtorExpStatement des;
if (fd.isNRVO() && s.finalbody && (des = s.finalbody.isDtorExpStatement()) !is null &&
fd.nrvo_var == des.var)
{
if (!(global.params.useExceptions && ClassDeclaration.throwable))
{
/* Don't need to call destructor at all, since it is nrvo
*/
replaceCurrent(s._body);
s._body.accept(this);
return;
}
/* Normally local variable dtors are called regardless exceptions.
* But for nrvo_var, its dtor should be called only when exception is thrown.
*
* Rewrite:
* try { s.body; } finally { nrvo_var.edtor; }
* // equivalent with:
* // s.body; scope(exit) nrvo_var.edtor;
* as:
* try { s.body; } catch(Throwable __o) { nrvo_var.edtor; throw __o; }
* // equivalent with:
* // s.body; scope(failure) nrvo_var.edtor;
*/
Statement sexception = new DtorExpStatement(Loc.initial, fd.nrvo_var.edtor, fd.nrvo_var);
Identifier id = Identifier.generateId("__o");
Statement handler = new PeelStatement(sexception);
if (sexception.blockExit(fd, false) & BE.fallthru)
{
auto ts = new ThrowStatement(Loc.initial, new IdentifierExp(Loc.initial, id));
ts.internalThrow = true;
handler = new CompoundStatement(Loc.initial, handler, ts);
}
auto catches = new Catches();
auto ctch = new Catch(Loc.initial, getThrowable(), id, handler);
ctch.internalCatch = true;
ctch.catchSemantic(sc); // Run semantic to resolve identifier '__o'
catches.push(ctch);
Statement s2 = new TryCatchStatement(Loc.initial, s._body, catches);
fd.flags &= ~FUNCFLAG.noEH;
replaceCurrent(s2);
s2.accept(this);
}
else
StatementRewriteWalker.visit(s);
}
}
enum FUNCFLAG : uint
{
purityInprocess = 1, /// working on determining purity
safetyInprocess = 2, /// working on determining safety
nothrowInprocess = 4, /// working on determining nothrow
nogcInprocess = 8, /// working on determining @nogc
returnInprocess = 0x10, /// working on inferring 'return' for parameters
inlineScanned = 0x20, /// function has been scanned for inline possibilities
inferScope = 0x40, /// infer 'scope' for parameters
hasCatches = 0x80, /// function has try-catch statements
compileTimeOnly = 0x100, /// is a compile time only function; no code will be generated for it
printf = 0x200, /// is a printf-like function
scanf = 0x400, /// is a scanf-like function
noreturn = 0x800, /// the function does not return
NRVO = 0x1000, /// Support for named return value optimization
naked = 0x2000, /// The function is 'naked' (see inline ASM)
generated = 0x4000, /// The function is compiler generated (e.g. `opCmp`)
introducing = 0x8000, /// If this function introduces the overload set
semantic3Errors = 0x10000, /// If errors in semantic3 this function's frame ptr
noEH = 0x20000, /// No exception unwinding is needed
inferRetType = 0x40000, /// Return type is to be inferred
dualContext = 0x80000, /// has a dual-context 'this' parameter
hasAlwaysInline = 0x100000, /// Contains references to functions that must be inlined
CRTCtor = 0x200000, /// Has attribute pragma(crt_constructor)
CRTDtor = 0x400000, /// Has attribute pragma(crt_destructor)
}
/***********************************************************
* Tuple of result identifier (possibly null) and statement.
* This is used to store out contracts: out(id){ ensure }
*/
extern (C++) struct Ensure
{
Identifier id;
Statement ensure;
Ensure syntaxCopy()
{
return Ensure(id, ensure.syntaxCopy());
}
/*****************************************
* Do syntax copy of an array of Ensure's.
*/
static Ensures* arraySyntaxCopy(Ensures* a)
{
Ensures* b = null;
if (a)
{
b = a.copy();
foreach (i, e; *a)
{
(*b)[i] = e.syntaxCopy();
}
}
return b;
}
}
/***********************************************************
*/
extern (C++) class FuncDeclaration : Declaration
{
Statements* frequires; /// in contracts
Ensures* fensures; /// out contracts
Statement frequire; /// lowered in contract
Statement fensure; /// lowered out contract
Statement fbody; /// function body
FuncDeclarations foverrides; /// functions this function overrides
FuncDeclaration fdrequire; /// function that does the in contract
FuncDeclaration fdensure; /// function that does the out contract
Expressions* fdrequireParams; /// argument list for __require
Expressions* fdensureParams; /// argument list for __ensure
const(char)* mangleString; /// mangled symbol created from mangleExact()
VarDeclaration vresult; /// result variable for out contracts
LabelDsymbol returnLabel; /// where the return goes
bool[size_t] isTypeIsolatedCache; /// cache for the potentially very expensive isTypeIsolated check
// used to prevent symbols in different
// scopes from having the same name
DsymbolTable localsymtab;
VarDeclaration vthis; /// 'this' parameter (member and nested)
VarDeclaration v_arguments; /// '_arguments' parameter
VarDeclaration v_argptr; /// '_argptr' variable
VarDeclarations* parameters; /// Array of VarDeclaration's for parameters
DsymbolTable labtab; /// statement label symbol table
Dsymbol overnext; /// next in overload list
FuncDeclaration overnext0; /// next in overload list (only used during IFTI)
Loc endloc; /// location of closing curly bracket
int vtblIndex = -1; /// for member functions, index into vtbl[]
ILS inlineStatusStmt = ILS.uninitialized;
ILS inlineStatusExp = ILS.uninitialized;
PINLINE inlining = PINLINE.default_;
int inlineNest; /// !=0 if nested inline
ForeachStatement fes; /// if foreach body, this is the foreach
BaseClass* interfaceVirtual; /// if virtual, but only appears in base interface vtbl[]
/** if !=NULL, then this is the type
of the 'introducing' function
this one is overriding
*/
Type tintro;
StorageClass storage_class2; /// storage class for template onemember's
// Things that should really go into Scope
/// 1 if there's a return exp; statement
/// 2 if there's a throw statement
/// 4 if there's an assert(0)
/// 8 if there's inline asm
/// 16 if there are multiple return statements
int hasReturnExp;
VarDeclaration nrvo_var; /// variable to replace with shidden
Symbol* shidden; /// hidden pointer passed to function
ReturnStatements* returns;
GotoStatements* gotos; /// Gotos with forward references
/// set if this is a known, builtin function we can evaluate at compile time
BUILTIN builtin = BUILTIN.unknown;
/// set if someone took the address of this function
int tookAddressOf;
bool requiresClosure; // this function needs a closure
/** local variables in this function which are referenced by nested functions
* (They'll get put into the "closure" for this function.)
*/
VarDeclarations closureVars;
/** Outer variables which are referenced by this nested function
* (the inverse of closureVars)
*/
VarDeclarations outerVars;
/// Sibling nested functions which called this one
FuncDeclarations siblingCallers;
FuncDeclarations *inlinedNestedCallees;
/// In case of failed `@safe` inference, store the error that made the function `@system` for
/// better diagnostics
AttributeViolation* safetyViolation;
/// Function flags: A collection of boolean packed for memory efficiency
/// See the `FUNCFLAG` enum
uint flags = FUNCFLAG.NRVO;
/**
* Data for a function declaration that is needed for the Objective-C
* integration.
*/
ObjcFuncDeclaration objc;
extern (D) this(const ref Loc loc, const ref Loc endloc, Identifier ident, StorageClass storage_class, Type type, bool noreturn = false)
{
super(loc, ident);
//printf("FuncDeclaration(id = '%s', type = %p)\n", id.toChars(), type);
//printf("storage_class = x%x\n", storage_class);
this.storage_class = storage_class;
this.type = type;
if (type)
{
// Normalize storage_class, because function-type related attributes
// are already set in the 'type' in parsing phase.
this.storage_class &= ~(STC.TYPECTOR | STC.FUNCATTR);
}
this.endloc = endloc;
if (noreturn)
this.flags |= FUNCFLAG.noreturn;
/* The type given for "infer the return type" is a TypeFunction with
* NULL for the return type.
*/
if (type && type.nextOf() is null)
this.flags |= FUNCFLAG.inferRetType;
}
static FuncDeclaration create(const ref Loc loc, const ref Loc endloc, Identifier id, StorageClass storage_class, Type type, bool noreturn = false)
{
return new FuncDeclaration(loc, endloc, id, storage_class, type, noreturn);
}
override FuncDeclaration syntaxCopy(Dsymbol s)
{
//printf("FuncDeclaration::syntaxCopy('%s')\n", toChars());
FuncDeclaration f = s ? cast(FuncDeclaration)s
: new FuncDeclaration(loc, endloc, ident, storage_class, type.syntaxCopy(), (flags & FUNCFLAG.noreturn) != 0);
f.frequires = frequires ? Statement.arraySyntaxCopy(frequires) : null;
f.fensures = fensures ? Ensure.arraySyntaxCopy(fensures) : null;
f.fbody = fbody ? fbody.syntaxCopy() : null;
return f;
}
/****************************************************
* Resolve forward reference of function signature -
* parameter types, return type, and attributes.
* Returns:
* false if any errors exist in the signature.
*/
final bool functionSemantic()
{
//printf("functionSemantic() %p %s\n", this, toChars());
if (!_scope)
return !errors;
this.cppnamespace = _scope.namespace;
if (!originalType) // semantic not yet run
{
TemplateInstance spec = isSpeculative();
uint olderrs = global.errors;
uint oldgag = global.gag;
if (global.gag && !spec)
global.gag = 0;
dsymbolSemantic(this, _scope);
global.gag = oldgag;
if (spec && global.errors != olderrs)
spec.errors = (global.errors - olderrs != 0);
if (olderrs != global.errors) // if errors compiling this function
return false;
}
// if inferring return type, sematic3 needs to be run
// - When the function body contains any errors, we cannot assume
// the inferred return type is valid.
// So, the body errors should become the function signature error.
if (inferRetType && type && !type.nextOf())
return functionSemantic3();
TemplateInstance ti;
if (isInstantiated() && !isVirtualMethod() &&
((ti = parent.isTemplateInstance()) is null || ti.isTemplateMixin() || ti.tempdecl.ident == ident))
{
AggregateDeclaration ad = isMemberLocal();
if (ad && ad.sizeok != Sizeok.done)
{
/* Currently dmd cannot resolve forward references per methods,
* then setting SIZOKfwd is too conservative and would break existing code.
* So, just stop method attributes inference until ad.dsymbolSemantic() done.
*/
//ad.sizeok = Sizeok.fwd;
}
else
return functionSemantic3() || !errors;
}
if (storage_class & STC.inference)
return functionSemantic3() || !errors;
return !errors;
}
/****************************************************
* Resolve forward reference of function body.
* Returns false if any errors exist in the body.
*/
final bool functionSemantic3()
{
if (semanticRun < PASS.semantic3 && _scope)
{
/* Forward reference - we need to run semantic3 on this function.
* If errors are gagged, and it's not part of a template instance,
* we need to temporarily ungag errors.
*/
TemplateInstance spec = isSpeculative();
uint olderrs = global.errors;
uint oldgag = global.gag;
if (global.gag && !spec)
global.gag = 0;
semantic3(this, _scope);
global.gag = oldgag;
// If it is a speculatively-instantiated template, and errors occur,
// we need to mark the template as having errors.
if (spec && global.errors != olderrs)
spec.errors = (global.errors - olderrs != 0);
if (olderrs != global.errors) // if errors compiling this function
return false;
}
return !errors && !this.hasSemantic3Errors();
}
/****************************************************
* Check that this function type is properly resolved.
* If not, report "forward reference error" and return true.
*/
extern (D) final bool checkForwardRef(const ref Loc loc)
{
if (!functionSemantic())
return true;
/* No deco means the functionSemantic() call could not resolve
* forward referenes in the type of this function.
*/
if (!type.deco)
{
bool inSemantic3 = (inferRetType && semanticRun >= PASS.semantic3);
.error(loc, "forward reference to %s`%s`",
(inSemantic3 ? "inferred return type of function " : "").ptr,
toChars());
return true;
}
return false;
}
// called from semantic3
/**
* Creates and returns the hidden parameters for this function declaration.
*
* Hidden parameters include the `this` parameter of a class, struct or
* nested function and the selector parameter for Objective-C methods.
*/
extern (D) final void declareThis(Scope* sc)
{
const bool dualCtx = (toParent2() != toParentLocal());
if (dualCtx)
this.flags |= FUNCFLAG.dualContext;
auto ad = isThis();
if (!dualCtx && !ad && !isNested())
{
vthis = null;
objc.selectorParameter = null;
return;
}
Type addModStc(Type t)
{
return t.addMod(type.mod).addStorageClass(storage_class);
}
if (dualCtx || isNested())
{
/* The 'this' for a nested function is the link to the
* enclosing function's stack frame.
* Note that nested functions and member functions are disjoint.
*/
Type tthis = addModStc(dualCtx ?
Type.tvoidptr.sarrayOf(2).pointerTo() :
Type.tvoid.pointerTo());
vthis = new VarDeclaration(loc, tthis, dualCtx ? Id.this2 : Id.capture, null);
vthis.storage_class |= STC.parameter | STC.nodtor;
}
else if (ad)
{
Type thandle = addModStc(ad.handleType());
vthis = new ThisDeclaration(loc, thandle);
vthis.storage_class |= STC.parameter;
if (thandle.ty == Tstruct)
{
vthis.storage_class |= STC.ref_;
}
}
if (auto tf = type.isTypeFunction())
{
if (tf.isreturn)
vthis.storage_class |= STC.return_;
if (tf.isScopeQual)
vthis.storage_class |= STC.scope_;
if (tf.isreturnscope)
vthis.storage_class |= STC.returnScope;
}
if (flags & FUNCFLAG.inferScope && !(vthis.storage_class & STC.scope_))
vthis.storage_class |= STC.maybescope;
vthis.dsymbolSemantic(sc);
if (!sc.insert(vthis))
assert(0);
vthis.parent = this;
if (ad)
objc.selectorParameter = .objc.createSelectorParameter(this, sc);
}
override final bool equals(const RootObject o) const
{
if (this == o)
return true;
if (auto s = isDsymbol(o))
{
auto fd1 = this;
auto fd2 = s.isFuncDeclaration();
if (!fd2)
return false;
auto fa1 = fd1.isFuncAliasDeclaration();
auto faf1 = fa1 ? fa1.toAliasFunc() : fd1;
auto fa2 = fd2.isFuncAliasDeclaration();
auto faf2 = fa2 ? fa2.toAliasFunc() : fd2;
if (fa1 && fa2)
{
return faf1.equals(faf2) && fa1.hasOverloads == fa2.hasOverloads;
}
bool b1 = fa1 !is null;
if (b1 && faf1.isUnique() && !fa1.hasOverloads)
b1 = false;
bool b2 = fa2 !is null;
if (b2 && faf2.isUnique() && !fa2.hasOverloads)
b2 = false;
if (b1 != b2)
return false;
return faf1.toParent().equals(faf2.toParent()) &&
faf1.ident.equals(faf2.ident) &&
faf1.type.equals(faf2.type);
}
return false;
}
/****************************************************
* Determine if 'this' overrides fd.
* Return !=0 if it does.
*/
final int overrides(FuncDeclaration fd)
{
int result = 0;
if (fd.ident == ident)
{
const cov = type.covariant(fd.type);
if (cov != Covariant.distinct)
{
ClassDeclaration cd1 = toParent().isClassDeclaration();
ClassDeclaration cd2 = fd.toParent().isClassDeclaration();
if (cd1 && cd2 && cd2.isBaseOf(cd1, null))
result = 1;
}
}
return result;
}
/*************************************************
* Find index of function in vtbl[0..dim] that
* this function overrides.
* Prefer an exact match to a covariant one.
* Params:
* vtbl = vtable to use
* dim = maximal vtable dimension
* Returns:
* -1 didn't find one
* -2 can't determine because of forward references
*/
final int findVtblIndex(Dsymbols* vtbl, int dim)
{
//printf("findVtblIndex() %s\n", toChars());
FuncDeclaration mismatch = null;
StorageClass mismatchstc = 0;
int mismatchvi = -1;
int exactvi = -1;
int bestvi = -1;
for (int vi = 0; vi < dim; vi++)
{
FuncDeclaration fdv = (*vtbl)[vi].isFuncDeclaration();
if (fdv && fdv.ident == ident)
{
if (type.equals(fdv.type)) // if exact match
{
if (fdv.parent.isClassDeclaration())
{
if (fdv.isFuture())
{
bestvi = vi;
continue; // keep looking
}
return vi; // no need to look further
}
if (exactvi >= 0)
{
error("cannot determine overridden function");
return exactvi;
}
exactvi = vi;
bestvi = vi;
continue;
}
StorageClass stc = 0;
const cov = type.covariant(fdv.type, &stc);
//printf("\tbaseclass cov = %d\n", cov);
final switch (cov)
{
case Covariant.distinct:
// types are distinct
break;
case Covariant.yes:
bestvi = vi; // covariant, but not identical
break;
// keep looking for an exact match
case Covariant.no:
mismatchvi = vi;
mismatchstc = stc;
mismatch = fdv; // overrides, but is not covariant
break;
// keep looking for an exact match
case Covariant.fwdref:
return -2; // forward references
}
}
}
if (_linkage == LINK.cpp && bestvi != -1)
{
StorageClass stc = 0;
FuncDeclaration fdv = (*vtbl)[bestvi].isFuncDeclaration();
assert(fdv && fdv.ident == ident);
if (type.covariant(fdv.type, &stc, /*cppCovariant=*/true) == Covariant.no)
{
/* https://issues.dlang.org/show_bug.cgi?id=22351
* Under D rules, `type` and `fdv.type` are covariant, but under C++ rules, they are not.
* For now, continue to allow D covariant rules to apply when `override` has been used,
* but issue a deprecation warning that this behaviour will change in the future.
* Otherwise, follow the C++ covariant rules, which will create a new vtable entry.
*/
if (isOverride())
{
/* @@@DEPRECATED_2.110@@@
* After deprecation period has ended, be sure to remove this entire `LINK.cpp` branch,
* but also the `cppCovariant` parameter from Type.covariant, and update the function
* so that both `LINK.cpp` covariant conditions within are always checked.
*/
.deprecation(loc, "overriding `extern(C++)` function `%s%s` with `const` qualified function `%s%s%s` is deprecated",
fdv.toPrettyChars(), fdv.type.toTypeFunction().parameterList.parametersTypeToChars(),
toPrettyChars(), type.toTypeFunction().parameterList.parametersTypeToChars(), type.modToChars());
const char* where = type.isNaked() ? "parameters" : "type";
deprecationSupplemental(loc, "Either remove `override`, or adjust the `const` qualifiers of the "
~ "overriding function %s", where);
}
else
{
// Treat as if Covariant.no
mismatchvi = bestvi;
mismatchstc = stc;
mismatch = fdv;
bestvi = -1;
}
}
}
if (bestvi == -1 && mismatch)
{
//type.print();
//mismatch.type.print();
//printf("%s %s\n", type.deco, mismatch.type.deco);
//printf("stc = %llx\n", mismatchstc);
if (mismatchstc)
{
// Fix it by modifying the type to add the storage classes
type = type.addStorageClass(mismatchstc);
bestvi = mismatchvi;
}
}
return bestvi;
}
/*********************************
* If function a function in a base class,
* return that base class.
* Returns:
* base class if overriding, null if not
*/
final BaseClass* overrideInterface()
{
for (ClassDeclaration cd = toParent2().isClassDeclaration(); cd; cd = cd.baseClass)
{
foreach (b; cd.interfaces)
{
auto v = findVtblIndex(&b.sym.vtbl, cast(int)b.sym.vtbl.dim);
if (v >= 0)
return b;
}
}
return null;
}
/****************************************************
* Overload this FuncDeclaration with the new one f.
* Return true if successful; i.e. no conflict.
*/
override bool overloadInsert(Dsymbol s)
{
//printf("FuncDeclaration::overloadInsert(s = %s) this = %s\n", s.toChars(), toChars());
assert(s != this);
AliasDeclaration ad = s.isAliasDeclaration();
if (ad)
{
if (overnext)
return overnext.overloadInsert(ad);
if (!ad.aliassym && ad.type.ty != Tident && ad.type.ty != Tinstance && ad.type.ty != Ttypeof)
{
//printf("\tad = '%s'\n", ad.type.toChars());
return false;
}
overnext = ad;
//printf("\ttrue: no conflict\n");
return true;
}
TemplateDeclaration td = s.isTemplateDeclaration();
if (td)
{
if (!td.funcroot)
td.funcroot = this;
if (overnext)
return overnext.overloadInsert(td);
overnext = td;
return true;
}
FuncDeclaration fd = s.isFuncDeclaration();
if (!fd)
return false;
version (none)
{
/* Disable this check because:
* const void foo();
* semantic() isn't run yet on foo(), so the const hasn't been
* applied yet.
*/
if (type)
{
printf("type = %s\n", type.toChars());
printf("fd.type = %s\n", fd.type.toChars());
}
// fd.type can be NULL for overloaded constructors
if (type && fd.type && fd.type.covariant(type) && fd.type.mod == type.mod && !isFuncAliasDeclaration())
{
//printf("\tfalse: conflict %s\n", kind());
return false;
}
}
if (overnext)
{
td = overnext.isTemplateDeclaration();
if (td)
fd.overloadInsert(td);
else
return overnext.overloadInsert(fd);
}
overnext = fd;
//printf("\ttrue: no conflict\n");
return true;
}
/********************************************
* Find function in overload list that exactly matches t.
*/
extern (D) final FuncDeclaration overloadExactMatch(Type t)
{
FuncDeclaration fd;
overloadApply(this, (Dsymbol s)
{
auto f = s.isFuncDeclaration();
if (!f)
return 0;
if (f.storage_class & STC.disable)
return 0;
if (t.equals(f.type))
{
fd = f;
return 1;
}
/* Allow covariant matches, as long as the return type
* is just a const conversion.
* This allows things like pure functions to match with an impure function type.
*/
if (t.ty == Tfunction)
{
auto tf = cast(TypeFunction)f.type;
if (tf.covariant(t) == Covariant.yes &&
tf.nextOf().implicitConvTo(t.nextOf()) >= MATCH.constant)
{
fd = f;
return 1;
}
}
return 0;
});
return fd;
}
/********************************************
* Find function in overload list that matches to the 'this' modifier.
* There's four result types.
*
* 1. If the 'tthis' matches only one candidate, it's an "exact match".
* Returns the function and 'hasOverloads' is set to false.
* eg. If 'tthis" is mutable and there's only one mutable method.
* 2. If there's two or more match candidates, but a candidate function will be
* a "better match".
* Returns the better match function but 'hasOverloads' is set to true.
* eg. If 'tthis' is mutable, and there's both mutable and const methods,
* the mutable method will be a better match.
* 3. If there's two or more match candidates, but there's no better match,
* Returns null and 'hasOverloads' is set to true to represent "ambiguous match".
* eg. If 'tthis' is mutable, and there's two or more mutable methods.
* 4. If there's no candidates, it's "no match" and returns null with error report.
* e.g. If 'tthis' is const but there's no const methods.
*/
extern (D) final FuncDeclaration overloadModMatch(const ref Loc loc, Type tthis, ref bool hasOverloads)
{
//printf("FuncDeclaration::overloadModMatch('%s')\n", toChars());
MatchAccumulator m;
overloadApply(this, (Dsymbol s)
{
auto f = s.isFuncDeclaration();
if (!f || f == m.lastf) // skip duplicates
return 0;
auto tf = f.type.toTypeFunction();
//printf("tf = %s\n", tf.toChars());
MATCH match;
if (tthis) // non-static functions are preferred than static ones
{
if (f.needThis())
match = f.isCtorDeclaration() ? MATCH.exact : MODmethodConv(tthis.mod, tf.mod);
else
match = MATCH.constant; // keep static function in overload candidates
}
else // static functions are preferred than non-static ones
{
if (f.needThis())
match = MATCH.convert;
else
match = MATCH.exact;
}
if (match == MATCH.nomatch)
return 0;
if (match > m.last) goto LcurrIsBetter;
if (match < m.last) goto LlastIsBetter;
// See if one of the matches overrides the other.
if (m.lastf.overrides(f)) goto LlastIsBetter;
if (f.overrides(m.lastf)) goto LcurrIsBetter;
//printf("\tambiguous\n");
m.nextf = f;
m.count++;
return 0;
LlastIsBetter:
//printf("\tlastbetter\n");
m.count++; // count up
return 0;
LcurrIsBetter:
//printf("\tisbetter\n");
if (m.last <= MATCH.convert)
{
// clear last secondary matching
m.nextf = null;
m.count = 0;
}
m.last = match;
m.lastf = f;
m.count++; // count up
return 0;
});
if (m.count == 1) // exact match
{
hasOverloads = false;
}
else if (m.count > 1) // better or ambiguous match
{
hasOverloads = true;
}
else // no match
{
hasOverloads = true;
auto tf = this.type.toTypeFunction();
assert(tthis);
assert(!MODimplicitConv(tthis.mod, tf.mod)); // modifier mismatch
{
OutBuffer thisBuf, funcBuf;
MODMatchToBuffer(&thisBuf, tthis.mod, tf.mod);
MODMatchToBuffer(&funcBuf, tf.mod, tthis.mod);
.error(loc, "%smethod %s is not callable using a %sobject",
funcBuf.peekChars(), this.toPrettyChars(), thisBuf.peekChars());
}
}
return m.lastf;
}
/********************************************
* find function template root in overload list
*/
extern (D) final TemplateDeclaration findTemplateDeclRoot()
{
FuncDeclaration f = this;
while (f && f.overnext)
{
//printf("f.overnext = %p %s\n", f.overnext, f.overnext.toChars());
TemplateDeclaration td = f.overnext.isTemplateDeclaration();
if (td)
return td;
f = f.overnext.isFuncDeclaration();
}
return null;
}
/********************************************
* Returns true if function was declared
* directly or indirectly in a unittest block
*/
final bool inUnittest()
{
Dsymbol f = this;
do
{
if (f.isUnitTestDeclaration())
return true;
f = f.toParent();
}
while (f);
return false;
}
/*************************************
* Determine partial specialization order of 'this' vs g.
* This is very similar to TemplateDeclaration::leastAsSpecialized().
* Returns:
* match 'this' is at least as specialized as g
* 0 g is more specialized than 'this'
*/
final MATCH leastAsSpecialized(FuncDeclaration g)
{
enum LOG_LEASTAS = 0;
static if (LOG_LEASTAS)
{
printf("%s.leastAsSpecialized(%s)\n", toChars(), g.toChars());
printf("%s, %s\n", type.toChars(), g.type.toChars());
}
/* This works by calling g() with f()'s parameters, and
* if that is possible, then f() is at least as specialized
* as g() is.
*/
TypeFunction tf = type.toTypeFunction();
TypeFunction tg = g.type.toTypeFunction();
/* If both functions have a 'this' pointer, and the mods are not
* the same and g's is not const, then this is less specialized.
*/
if (needThis() && g.needThis() && tf.mod != tg.mod)
{
if (isCtorDeclaration())
{
if (!MODimplicitConv(tg.mod, tf.mod))
return MATCH.nomatch;
}
else
{
if (!MODimplicitConv(tf.mod, tg.mod))
return MATCH.nomatch;
}
}
/* Create a dummy array of arguments out of the parameters to f()
*/
Expressions args;
foreach (u, p; tf.parameterList)
{
Expression e;
if (p.isReference())
{
e = new IdentifierExp(Loc.initial, p.ident);
e.type = p.type;
}
else
e = p.type.defaultInitLiteral(Loc.initial);
args.push(e);
}
MATCH m = tg.callMatch(null, args[], 1);
if (m > MATCH.nomatch)
{
/* A variadic parameter list is less specialized than a
* non-variadic one.
*/
if (tf.parameterList.varargs && !tg.parameterList.varargs)
goto L1; // less specialized
static if (LOG_LEASTAS)
{
printf(" matches %d, so is least as specialized\n", m);
}
return m;
}
L1:
static if (LOG_LEASTAS)
{
printf(" doesn't match, so is not as specialized\n");
}
return MATCH.nomatch;
}
/********************************
* Searches for a label with the given identifier. This function will insert a new
* `LabelDsymbol` into `labtab` if it does not contain a mapping for `ident`.
*
* Params:
* ident = identifier of the requested label
* loc = location used when creating a new `LabelDsymbol`
*
* Returns: the `LabelDsymbol` for `ident`
*/
final LabelDsymbol searchLabel(Identifier ident, const ref Loc loc = Loc.initial)
{
Dsymbol s;
if (!labtab)
labtab = new DsymbolTable(); // guess we need one
s = labtab.lookup(ident);
if (!s)
{
s = new LabelDsymbol(ident, loc);
labtab.insert(s);
}
return cast(LabelDsymbol)s;
}
/*****************************************
* Determine lexical level difference from `this` to nested function `fd`.
* Params:
* fd = target of call
* intypeof = !=0 if inside typeof
* Returns:
* 0 same level
* >0 decrease nesting by number
* -1 increase nesting by 1 (`fd` is nested within `this`)
* LevelError error, `this` cannot call `fd`
*/
final int getLevel(FuncDeclaration fd, int intypeof)
{
//printf("FuncDeclaration::getLevel(fd = '%s')\n", fd.toChars());
Dsymbol fdparent = fd.toParent2();
if (fdparent == this)
return -1;
Dsymbol s = this;
int level = 0;
while (fd != s && fdparent != s.toParent2())
{
//printf("\ts = %s, '%s'\n", s.kind(), s.toChars());
if (auto thisfd = s.isFuncDeclaration())
{
if (!thisfd.isNested() && !thisfd.vthis && !intypeof)
return LevelError;
}
else
{
if (auto thiscd = s.isAggregateDeclaration())
{
/* AggregateDeclaration::isNested returns true only when
* it has a hidden pointer.
* But, calling the function belongs unrelated lexical scope
* is still allowed inside typeof.
*
* struct Map(alias fun) {
* typeof({ return fun(); }) RetType;
* // No member function makes Map struct 'not nested'.
* }
*/
if (!thiscd.isNested() && !intypeof)
return LevelError;
}
else
return LevelError;
}
s = s.toParentP(fd);
assert(s);
level++;
}
return level;
}
/***********************************
* Determine lexical level difference from `this` to nested function `fd`.
* Issue error if `this` cannot call `fd`.
*
* Params:
* loc = location for error messages
* sc = context
* fd = target of call
* decl = The `Declaration` that triggered this check.
* Used to provide a better error message only.
* Returns:
* 0 same level
* >0 decrease nesting by number
* -1 increase nesting by 1 (`fd` is nested within 'this')
* LevelError error
*/
final int getLevelAndCheck(const ref Loc loc, Scope* sc, FuncDeclaration fd,
Declaration decl)
{
int level = getLevel(fd, sc.intypeof);
if (level != LevelError)
return level;
// Don't give error if in template constraint
if (!(sc.flags & SCOPE.constraint))
{
const(char)* xstatic = isStatic() ? "`static` " : "";
// better diagnostics for static functions
.error(loc, "%s%s `%s` cannot access %s `%s` in frame of function `%s`",
xstatic, kind(), toPrettyChars(), decl.kind(), decl.toChars(),
fd.toPrettyChars());
.errorSupplemental(decl.loc, "`%s` declared here", decl.toChars());
return LevelError;
}
return 1;
}
enum LevelError = -2;
override const(char)* toPrettyChars(bool QualifyTypes = false)
{
if (isMain())
return "D main";
else
return Dsymbol.toPrettyChars(QualifyTypes);
}
/** for diagnostics, e.g. 'int foo(int x, int y) pure' */
final const(char)* toFullSignature()
{
OutBuffer buf;
functionToBufferWithIdent(type.toTypeFunction(), &buf, toChars(), isStatic);
return buf.extractChars();
}
final bool isMain() const
{
return ident == Id.main && resolvedLinkage() != LINK.c && !isMember() && !isNested();
}
final bool isCMain() const
{
return ident == Id.main && resolvedLinkage() == LINK.c && !isMember() && !isNested();
}
final bool isWinMain() const
{
//printf("FuncDeclaration::isWinMain() %s\n", toChars());
version (none)
{
bool x = ident == Id.WinMain && resolvedLinkage() != LINK.c && !isMember();
printf("%s\n", x ? "yes" : "no");
return x;
}
else
{
return ident == Id.WinMain && resolvedLinkage() != LINK.c && !isMember();
}
}
final bool isDllMain() const
{
return ident == Id.DllMain && resolvedLinkage() != LINK.c && !isMember();
}
final bool isRtInit() const
{
return ident == Id.rt_init && resolvedLinkage() == LINK.c && !isMember() && !isNested();
}
override final bool isExport() const
{
return visibility.kind == Visibility.Kind.export_;
}
override final bool isImportedSymbol() const
{
//printf("isImportedSymbol()\n");
//printf("protection = %d\n", visibility);
return (visibility.kind == Visibility.Kind.export_) && !fbody;
}
override final bool isCodeseg() const pure nothrow @nogc @safe
{
return true; // functions are always in the code segment
}
override final bool isOverloadable() const
{
return true; // functions can be overloaded
}
/***********************************
* Override so it can work even if semantic() hasn't yet
* been run.
*/
override final bool isAbstract()
{
if (storage_class & STC.abstract_)
return true;
if (semanticRun >= PASS.semanticdone)
return false;
if (_scope)
{
if (_scope.stc & STC.abstract_)
return true;
parent = _scope.parent;
Dsymbol parent = toParent();
if (parent.isInterfaceDeclaration())
return true;
}
return false;
}
/**********************************
* Decide if attributes for this function can be inferred from examining
* the function body.
* Returns:
* true if can
*/
final bool canInferAttributes(Scope* sc)
{
if (!fbody)
return false;
if (isVirtualMethod() &&
/*
* https://issues.dlang.org/show_bug.cgi?id=21719
*
* If we have an auto virtual function we can infer
* the attributes.
*/
!(inferRetType && !isCtorDeclaration()))
return false; // since they may be overridden
if (sc.func &&
/********** this is for backwards compatibility for the moment ********/
(!isMember() || sc.func.isSafeBypassingInference() && !isInstantiated()))
return true;
if (isFuncLiteralDeclaration() || // externs are not possible with literals
(storage_class & STC.inference) || // do attribute inference
(inferRetType && !isCtorDeclaration()))
return true;
if (isInstantiated())
{
auto ti = parent.isTemplateInstance();
if (ti is null || ti.isTemplateMixin() || ti.tempdecl.ident == ident)
return true;
}
return false;
}
/*****************************************
* Initialize for inferring the attributes of this function.
*/
final void initInferAttributes()
{
//printf("initInferAttributes() for %s (%s)\n", toPrettyChars(), ident.toChars());
TypeFunction tf = type.toTypeFunction();
if (tf.purity == PURE.impure) // purity not specified
flags |= FUNCFLAG.purityInprocess;
if (tf.trust == TRUST.default_)
flags |= FUNCFLAG.safetyInprocess;
if (!tf.isnothrow)
flags |= FUNCFLAG.nothrowInprocess;
if (!tf.isnogc)
flags |= FUNCFLAG.nogcInprocess;
if (!isVirtual() || this.isIntroducing())
flags |= FUNCFLAG.returnInprocess;
// Initialize for inferring STC.scope_
flags |= FUNCFLAG.inferScope;
}
final PURE isPure()
{
//printf("FuncDeclaration::isPure() '%s'\n", toChars());
TypeFunction tf = type.toTypeFunction();
if (flags & FUNCFLAG.purityInprocess)
setImpure();
if (tf.purity == PURE.fwdref)
tf.purityLevel();
PURE purity = tf.purity;
if (purity > PURE.weak && isNested())
purity = PURE.weak;
if (purity > PURE.weak && needThis())
{
// The attribute of the 'this' reference affects purity strength
if (type.mod & MODFlags.immutable_)
{
}
else if (type.mod & (MODFlags.const_ | MODFlags.wild) && purity >= PURE.const_)
purity = PURE.const_;
else
purity = PURE.weak;
}
tf.purity = purity;
// ^ This rely on the current situation that every FuncDeclaration has a
// unique TypeFunction.
return purity;
}
final PURE isPureBypassingInference()
{
if (flags & FUNCFLAG.purityInprocess)
return PURE.fwdref;
else
return isPure();
}
/**************************************
* The function is doing something impure,
* so mark it as impure.
* If there's a purity error, return true.
*/
extern (D) final bool setImpure()
{
if (flags & FUNCFLAG.purityInprocess)
{
flags &= ~FUNCFLAG.purityInprocess;
if (fes)
fes.func.setImpure();
}
else if (isPure())
return true;
return false;
}
final bool isSafe()
{
if (flags & FUNCFLAG.safetyInprocess)
setUnsafe();
return type.toTypeFunction().trust == TRUST.safe;
}
final bool isSafeBypassingInference()
{
return !(flags & FUNCFLAG.safetyInprocess) && isSafe();
}
final bool isTrusted()
{
if (flags & FUNCFLAG.safetyInprocess)
setUnsafe();
return type.toTypeFunction().trust == TRUST.trusted;
}
/**************************************
* The function is doing something unsafe, so mark it as unsafe.
*
* Params:
* gag = surpress error message (used in escape.d)
* loc = location of error
* fmt = printf-style format string
* arg0 = (optional) argument for first %s format specifier
* arg1 = (optional) argument for second %s format specifier
* arg2 = (optional) argument for third %s format specifier
* Returns: whether there's a safe error
*/
extern (D) final bool setUnsafe(
bool gag = false, Loc loc = Loc.init, const(char)* fmt = null,
RootObject arg0 = null, RootObject arg1 = null, RootObject arg2 = null)
{
if (flags & FUNCFLAG.safetyInprocess)
{
flags &= ~FUNCFLAG.safetyInprocess;
type.toTypeFunction().trust = TRUST.system;
if (fmt || arg0)
safetyViolation = new AttributeViolation(loc, fmt, arg0, arg1, arg2);
if (fes)
fes.func.setUnsafe();
}
else if (isSafe())
{
if (!gag && fmt)
.error(loc, fmt, arg0 ? arg0.toChars() : "", arg1 ? arg1.toChars() : "", arg2 ? arg2.toChars() : "");
return true;
}
return false;
}
/**************************************
* The function is calling `@system` function `f`, so mark it as unsafe.
*
* Params:
* f = function being called (needed for diagnostic of inferred functions)
* Returns: whether there's a safe error
*/
extern (D) final bool setUnsafeCall(FuncDeclaration f)
{
return setUnsafe(false, f.loc, null, f, null);
}
final bool isNogc()
{
//printf("isNogc() %s, inprocess: %d\n", toChars(), !!(flags & FUNCFLAG.nogcInprocess));
if (flags & FUNCFLAG.nogcInprocess)
setGC();
return type.toTypeFunction().isnogc;
}
final bool isNogcBypassingInference()
{
return !(flags & FUNCFLAG.nogcInprocess) && isNogc();
}
final bool isNRVO() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.NRVO);
}
final void isNRVO(bool v) pure nothrow @safe @nogc
{
if (v) this.flags |= FUNCFLAG.NRVO;
else this.flags &= ~FUNCFLAG.NRVO;
}
final bool isNaked() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.naked);
}
final void isNaked(bool v) @safe pure nothrow @nogc
{
if (v) this.flags |= FUNCFLAG.naked;
else this.flags &= ~FUNCFLAG.naked;
}
final bool isGenerated() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.generated);
}
final void isGenerated(bool v) pure nothrow @safe @nogc
{
if (v) this.flags |= FUNCFLAG.generated;
else this.flags &= ~FUNCFLAG.generated;
}
final bool isIntroducing() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.introducing);
}
final bool hasSemantic3Errors() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.semantic3Errors);
}
final bool hasNoEH() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.noEH);
}
final bool inferRetType() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.inferRetType);
}
final bool hasDualContext() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.dualContext);
}
final bool hasAlwaysInlines() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.hasAlwaysInline);
}
final bool isCrtCtor() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.CRTCtor);
}
final void isCrtCtor(bool v) @safe pure nothrow @nogc
{
if (v) this.flags |= FUNCFLAG.CRTCtor;
else this.flags &= ~FUNCFLAG.CRTCtor;
}
final bool isCrtDtor() const scope @safe pure nothrow @nogc
{
return !!(this.flags & FUNCFLAG.CRTDtor);
}
final void isCrtDtor(bool v) @safe pure nothrow @nogc
{
if (v) this.flags |= FUNCFLAG.CRTDtor;
else this.flags &= ~FUNCFLAG.CRTDtor;
}
/**************************************
* The function is doing something that may allocate with the GC,
* so mark it as not nogc (not no-how).
* Returns:
* true if function is marked as @nogc, meaning a user error occurred
*/
extern (D) final bool setGC()
{
//printf("setGC() %s\n", toChars());
if (flags & FUNCFLAG.nogcInprocess && semanticRun < PASS.semantic3 && _scope)
{
this.semantic2(_scope);
this.semantic3(_scope);
}
if (flags & FUNCFLAG.nogcInprocess)
{
flags &= ~FUNCFLAG.nogcInprocess;
type.toTypeFunction().isnogc = false;
if (fes)
fes.func.setGC();
}
else if (isNogc())
return true;
return false;
}
extern (D) final void printGCUsage(const ref Loc loc, const(char)* warn)
{
if (!global.params.vgc)
return;
Module m = getModule();
if (m && m.isRoot() && !inUnittest())
{
message(loc, "vgc: %s", warn);
}
}
/********************************************
* See if pointers from function parameters, mutable globals, or uplevel functions
* could leak into return value.
* Returns:
* true if the function return value is isolated from
* any inputs to the function
*/
extern (D) final bool isReturnIsolated()
{
//printf("isReturnIsolated(this: %s)\n", this.toChars);
TypeFunction tf = type.toTypeFunction();
assert(tf.next);
Type treti = tf.next;
if (tf.isref)
return isTypeIsolatedIndirect(treti); // check influence from parameters
return isTypeIsolated(treti);
}
/********************
* See if pointers from function parameters, mutable globals, or uplevel functions
* could leak into type `t`.
* Params:
* t = type to check if it is isolated
* Returns:
* true if `t` is isolated from
* any inputs to the function
*/
extern (D) final bool isTypeIsolated(Type t)
{
StringTable!Type parentTypes;
const uniqueTypeID = t.getUniqueID();
if (uniqueTypeID)
{
const cacheResultPtr = uniqueTypeID in isTypeIsolatedCache;
if (cacheResultPtr !is null)
return *cacheResultPtr;
parentTypes._init();
const isIsolated = isTypeIsolated(t, parentTypes);
isTypeIsolatedCache[uniqueTypeID] = isIsolated;
return isIsolated;
}
else
{
parentTypes._init();
return isTypeIsolated(t, parentTypes);
}
}
///ditto
extern (D) final bool isTypeIsolated(Type t, ref StringTable!Type parentTypes)
{
//printf("this: %s, isTypeIsolated(t: %s)\n", this.toChars(), t.toChars());
t = t.baseElemOf();
switch (t.ty)
{
case Tarray:
case Tpointer:
return isTypeIsolatedIndirect(t.nextOf()); // go down one level
case Taarray:
case Tclass:
return isTypeIsolatedIndirect(t);
case Tstruct:
/* Drill down and check the struct's fields
*/
auto sym = t.toDsymbol(null).isStructDeclaration();
const tName = t.toChars.toDString;
const entry = parentTypes.insert(tName, t);
if (entry == null)
{
//we've already seen this type in a parent, not isolated
return false;
}
foreach (v; sym.fields)
{
Type tmi = v.type.addMod(t.mod);
//printf("\tt = %s, v: %s, vtype: %s, tmi = %s\n",
// t.toChars(), v.toChars(), v.type.toChars(), tmi.toChars());
if (!isTypeIsolated(tmi, parentTypes))
return false;
}
return true;
default:
return true;
}
}
/********************************************
* Params:
* t = type of object to test one level of indirection down
* Returns:
* true if an object typed `t` has no indirections
* which could have come from the function's parameters, mutable
* globals, or uplevel functions.
*/
private bool isTypeIsolatedIndirect(Type t)
{
//printf("isTypeIsolatedIndirect(t: %s)\n", t.toChars());
assert(t);
/* Since `t` is one level down from an indirection, it could pick
* up a reference to a mutable global or an outer function, so
* return false.
*/
if (!isPureBypassingInference() || isNested())
return false;
TypeFunction tf = type.toTypeFunction();
//printf("isTypeIsolatedIndirect(%s) t = %s\n", tf.toChars(), t.toChars());
foreach (i, fparam; tf.parameterList)
{
Type tp = fparam.type;
if (!tp)
continue;
if (fparam.isLazy() || fparam.isReference())
{
if (!traverseIndirections(tp, t))
return false;
continue;
}
/* Goes down one level of indirection, then calls traverseIndirection() on
* the result.
* Returns:
* true if t is isolated from tp
*/
static bool traverse(Type tp, Type t)
{
tp = tp.baseElemOf();
switch (tp.ty)
{
case Tarray:
case Tpointer:
return traverseIndirections(tp.nextOf(), t);
case Taarray:
case Tclass:
return traverseIndirections(tp, t);
case Tstruct:
/* Drill down and check the struct's fields
*/
auto sym = tp.toDsymbol(null).isStructDeclaration();
foreach (v; sym.fields)
{
Type tprmi = v.type.addMod(tp.mod);
//printf("\ttp = %s, tprmi = %s\n", tp.toChars(), tprmi.toChars());
if (!traverse(tprmi, t))
return false;
}
return true;
default:
return true;
}
}
if (!traverse(tp, t))
return false;
}
// The 'this' reference is a parameter, too
if (AggregateDeclaration ad = isCtorDeclaration() ? null : isThis())
{
Type tthis = ad.getType().addMod(tf.mod);
//printf("\ttthis = %s\n", tthis.toChars());
if (!traverseIndirections(tthis, t))
return false;
}
return true;
}
/****************************************
* Determine if function needs a static frame pointer.
* Returns:
* `true` if function is really nested within other function.
* Contracts:
* If isNested() returns true, isThis() should return false,
* unless the function needs a dual-context pointer.
*/
bool isNested() const
{
auto f = toAliasFunc();
//printf("\ttoParent2() = '%s'\n", f.toParent2().toChars());
return ((f.storage_class & STC.static_) == 0) &&
(f._linkage == LINK.d) &&
(f.toParent2().isFuncDeclaration() !is null ||
f.toParent2() !is f.toParentLocal());
}
/****************************************
* Determine if function is a non-static member function
* that has an implicit 'this' expression.
* Returns:
* The aggregate it is a member of, or null.
* Contracts:
* Both isThis() and isNested() should return true if function needs a dual-context pointer,
* otherwise if isThis() returns true, isNested() should return false.
*/
override inout(AggregateDeclaration) isThis() inout
{
//printf("+FuncDeclaration::isThis() '%s'\n", toChars());
auto ad = (storage_class & STC.static_) ? .objc.isThis(this) : isMemberLocal();
//printf("-FuncDeclaration::isThis() %p\n", ad);
return ad;
}
override final bool needThis()
{
//printf("FuncDeclaration::needThis() '%s'\n", toChars());
return toAliasFunc().isThis() !is null;
}
// Determine if a function is pedantically virtual
final bool isVirtualMethod()
{
if (toAliasFunc() != this)
return toAliasFunc().isVirtualMethod();
//printf("FuncDeclaration::isVirtualMethod() %s\n", toChars());
if (!isVirtual())
return false;
// If it's a final method, and does not override anything, then it is not virtual
if (isFinalFunc() && foverrides.dim == 0)
{
return false;
}
return true;
}
// Determine if function goes into virtual function pointer table
bool isVirtual() const
{
if (toAliasFunc() != this)
return toAliasFunc().isVirtual();
auto p = toParent();
if (!isMember || !p.isClassDeclaration)
return false;
if (p.isClassDeclaration.classKind == ClassKind.objc)
return .objc.isVirtual(this);
version (none)
{
printf("FuncDeclaration::isVirtual(%s)\n", toChars());
printf("isMember:%p isStatic:%d private:%d ctor:%d !Dlinkage:%d\n", isMember(), isStatic(), visibility == Visibility.Kind.private_, isCtorDeclaration(), linkage != LINK.d);
printf("result is %d\n", isMember() && !(isStatic() || visibility == Visibility.Kind.private_ || visibility == Visibility.Kind.package_) && p.isClassDeclaration() && !(p.isInterfaceDeclaration() && isFinalFunc()));
}
return !(isStatic() || visibility.kind == Visibility.Kind.private_ || visibility.kind == Visibility.Kind.package_) && !(p.isInterfaceDeclaration() && isFinalFunc());
}
final bool isFinalFunc() const
{
if (toAliasFunc() != this)
return toAliasFunc().isFinalFunc();
version (none)
{{
auto cd = toParent().isClassDeclaration();
printf("FuncDeclaration::isFinalFunc(%s), %x\n", toChars(), Declaration.isFinal());
printf("%p %d %d %d\n", isMember(), isStatic(), Declaration.isFinal(), ((cd = toParent().isClassDeclaration()) !is null && cd.storage_class & STC.final_));
printf("result is %d\n", isMember() && (Declaration.isFinal() || (cd !is null && cd.storage_class & STC.final_)));
if (cd)
printf("\tmember of %s\n", cd.toChars());
}}
if (!isMember())
return false;
if (Declaration.isFinal())
return true;
auto cd = toParent().isClassDeclaration();
return (cd !is null) && (cd.storage_class & STC.final_);
}
bool addPreInvariant()
{
auto ad = isThis();
ClassDeclaration cd = ad ? ad.isClassDeclaration() : null;
return (ad && !(cd && cd.isCPPclass()) && global.params.useInvariants == CHECKENABLE.on && (visibility.kind == Visibility.Kind.protected_ || visibility.kind == Visibility.Kind.public_ || visibility.kind == Visibility.Kind.export_) && !this.isNaked());
}
bool addPostInvariant()
{
auto ad = isThis();
ClassDeclaration cd = ad ? ad.isClassDeclaration() : null;
return (ad && !(cd && cd.isCPPclass()) && ad.inv && global.params.useInvariants == CHECKENABLE.on && (visibility.kind == Visibility.Kind.protected_ || visibility.kind == Visibility.Kind.public_ || visibility.kind == Visibility.Kind.export_) && !this.isNaked());
}
override const(char)* kind() const
{
return this.isGenerated() ? "generated function" : "function";
}
/********************************************
* Returns:
* true if there are no overloads of this function
*/
final bool isUnique() const
{
bool result = false;
overloadApply(cast() this, (Dsymbol s)
{
auto f = s.isFuncDeclaration();
if (!f)
return 0;
if (result)
{
result = false;
return 1; // ambiguous, done
}
else
{
result = true;
return 0;
}
});
return result;
}
/*********************************************
* In the current function, we are calling 'this' function.
* 1. Check to see if the current function can call 'this' function, issue error if not.
* 2. If the current function is not the parent of 'this' function, then add
* the current function to the list of siblings of 'this' function.
* 3. If the current function is a literal, and it's accessing an uplevel scope,
* then mark it as a delegate.
* Returns true if error occurs.
*/
extern (D) final bool checkNestedReference(Scope* sc, const ref Loc loc)
{
//printf("FuncDeclaration::checkNestedReference() %s\n", toPrettyChars());
if (auto fld = this.isFuncLiteralDeclaration())
{
if (fld.tok == TOK.reserved)
{
fld.tok = TOK.function_;
fld.vthis = null;
}
}
if (!parent || parent == sc.parent)
return false;
if (ident == Id.require || ident == Id.ensure)
return false;
if (!isThis() && !isNested())
return false;
// The current function
FuncDeclaration fdthis = sc.parent.isFuncDeclaration();
if (!fdthis)
return false; // out of function scope
Dsymbol p = toParentLocal();
Dsymbol p2 = toParent2();
// Function literals from fdthis to p must be delegates
ensureStaticLinkTo(fdthis, p);
if (p != p2)
ensureStaticLinkTo(fdthis, p2);
if (isNested())
{
// The function that this function is in
bool checkEnclosing(FuncDeclaration fdv)
{
if (!fdv)
return false;
if (fdv == fdthis)
return false;
//printf("this = %s in [%s]\n", this.toChars(), this.loc.toChars());
//printf("fdv = %s in [%s]\n", fdv .toChars(), fdv .loc.toChars());
//printf("fdthis = %s in [%s]\n", fdthis.toChars(), fdthis.loc.toChars());
// Add this function to the list of those which called us
if (fdthis != this)
{
bool found = false;
for (size_t i = 0; i < siblingCallers.dim; ++i)
{
if (siblingCallers[i] == fdthis)
found = true;
}
if (!found)
{
//printf("\tadding sibling %s to %s\n", fdthis.toPrettyChars(), toPrettyChars());
if (!sc.intypeof && !(sc.flags & SCOPE.compile))
{
siblingCallers.push(fdthis);
}
}
}
const lv = fdthis.getLevelAndCheck(loc, sc, fdv, this);
if (lv == LevelError)
return true; // error
if (lv == -1)
return false; // downlevel call
if (lv == 0)
return false; // same level call
return false; // Uplevel call
}
if (checkEnclosing(p.isFuncDeclaration()))
return true;
if (checkEnclosing(p == p2 ? null : p2.isFuncDeclaration()))
return true;
}
return false;
}
/*******************************
* Look at all the variables in this function that are referenced
* by nested functions, and determine if a closure needs to be
* created for them.
*/
final bool needsClosure()
{
/* Need a closure for all the closureVars[] if any of the
* closureVars[] are accessed by a
* function that escapes the scope of this function.
* We take the conservative approach and decide that a function needs
* a closure if it:
* 1) is a virtual function
* 2) has its address taken
* 3) has a parent that escapes
* 4) calls another nested function that needs a closure
*
* Note that since a non-virtual function can be called by
* a virtual one, if that non-virtual function accesses a closure
* var, the closure still has to be taken. Hence, we check for isThis()
* instead of isVirtual(). (thanks to David Friedman)
*
* When the function returns a local struct or class, `requiresClosure`
* is already set to `true` upon entering this function when the
* struct/class refers to a local variable and a closure is needed.
*/
//printf("FuncDeclaration::needsClosure() %s\n", toChars());
if (requiresClosure)
goto Lyes;
for (size_t i = 0; i < closureVars.dim; i++)
{
VarDeclaration v = closureVars[i];
//printf("\tv = %s\n", v.toChars());
for (size_t j = 0; j < v.nestedrefs.dim; j++)
{
FuncDeclaration f = v.nestedrefs[j];
assert(f != this);
/* __require and __ensure will always get called directly,
* so they never make outer functions closure.
*/
if (f.ident == Id.require || f.ident == Id.ensure)
continue;
//printf("\t\tf = %p, %s, isVirtual=%d, isThis=%p, tookAddressOf=%d\n", f, f.toChars(), f.isVirtual(), f.isThis(), f.tookAddressOf);
/* Look to see if f escapes. We consider all parents of f within
* this, and also all siblings which call f; if any of them escape,
* so does f.
* Mark all affected functions as requiring closures.
*/
for (Dsymbol s = f; s && s != this; s = s.toParentP(this))
{
FuncDeclaration fx = s.isFuncDeclaration();
if (!fx)
continue;
if (fx.isThis() || fx.tookAddressOf)
{
//printf("\t\tfx = %s, isVirtual=%d, isThis=%p, tookAddressOf=%d\n", fx.toChars(), fx.isVirtual(), fx.isThis(), fx.tookAddressOf);
/* Mark as needing closure any functions between this and f
*/
markAsNeedingClosure((fx == f) ? fx.toParentP(this) : fx, this);
requiresClosure = true;
}
/* We also need to check if any sibling functions that
* called us, have escaped. This is recursive: we need
* to check the callers of our siblings.
*/
if (checkEscapingSiblings(fx, this))
requiresClosure = true;
/* https://issues.dlang.org/show_bug.cgi?id=12406
* Iterate all closureVars to mark all descendant
* nested functions that access to the closing context of this function.
*/
}
}
}
if (requiresClosure)
goto Lyes;
return false;
Lyes:
return true;
}
/***********************************************
* Check that the function contains any closure.
* If it's @nogc, report suitable errors.
* This is mostly consistent with FuncDeclaration::needsClosure().
*
* Returns:
* true if any errors occur.
*/
extern (C++) final bool checkClosure()
{
//printf("checkClosure() %s\n", toChars());
if (!needsClosure())
return false;
if (setGC())
{
error("is `@nogc` yet allocates closure for `%s()` with the GC", toChars());
if (global.gag) // need not report supplemental errors
return true;
}
else if (global.params.betterC)
{
error("is `-betterC` yet allocates closure for `%s()` with the GC", toChars());
if (global.gag) // need not report supplemental errors
return true;
}
else
{
printGCUsage(loc, "using closure causes GC allocation");
return false;
}
FuncDeclarations a;
foreach (v; closureVars)
{
foreach (f; v.nestedrefs)
{
assert(f !is this);
LcheckAncestorsOfANestedRef:
for (Dsymbol s = f; s && s !is this; s = s.toParentP(this))
{
auto fx = s.isFuncDeclaration();
if (!fx)
continue;
if (fx.isThis() ||
fx.tookAddressOf ||
checkEscapingSiblings(fx, this))
{
foreach (f2; a)
{
if (f2 == f)
break LcheckAncestorsOfANestedRef;
}
a.push(f);
.errorSupplemental(f.loc, "`%s` closes over variable `%s` at %s",
f.toPrettyChars(), v.toChars(), v.loc.toChars());
break LcheckAncestorsOfANestedRef;
}
}
}
}
return true;
}
/***********************************************
* Determine if function's variables are referenced by a function
* nested within it.
*/
final bool hasNestedFrameRefs()
{
if (closureVars.dim)
return true;
/* If a virtual function has contracts, assume its variables are referenced
* by those contracts, even if they aren't. Because they might be referenced
* by the overridden or overriding function's contracts.
* This can happen because frequire and fensure are implemented as nested functions,
* and they can be called directly by an overriding function and the overriding function's
* context had better match, or
* https://issues.dlang.org/show_bug.cgi?id=7335 will bite.
*/
if (fdrequire || fdensure)
return true;
if (foverrides.dim && isVirtualMethod())
{
for (size_t i = 0; i < foverrides.dim; i++)
{
FuncDeclaration fdv = foverrides[i];
if (fdv.hasNestedFrameRefs())
return true;
}
}
return false;
}
/****************************************************
* Check whether result variable can be built.
* Returns:
* `true` if the function has a return type that
* is different from `void`.
*/
extern (D) private bool canBuildResultVar()
{
auto f = cast(TypeFunction)type;
return f && f.nextOf() && f.nextOf().toBasetype().ty != Tvoid;
}
/****************************************************
* Declare result variable lazily.
*/
extern (D) final void buildResultVar(Scope* sc, Type tret)
{
if (!vresult)
{
Loc loc = fensure ? fensure.loc : this.loc;
/* If inferRetType is true, tret may not be a correct return type yet.
* So, in here it may be a temporary type for vresult, and after
* fbody.dsymbolSemantic() running, vresult.type might be modified.
*/
vresult = new VarDeclaration(loc, tret, Id.result, null);
vresult.storage_class |= STC.nodtor | STC.temp;
if (!isVirtual())
vresult.storage_class |= STC.const_;
vresult.storage_class |= STC.result;
// set before the semantic() for checkNestedReference()
vresult.parent = this;
}
if (sc && vresult.semanticRun == PASS.initial)
{
TypeFunction tf = type.toTypeFunction();
if (tf.isref)
vresult.storage_class |= STC.ref_;
vresult.type = tret;
vresult.dsymbolSemantic(sc);
if (!sc.insert(vresult))
error("out result %s is already defined", vresult.toChars());
assert(vresult.parent == this);
}
}
/****************************************************
* Merge into this function the 'in' contracts of all it overrides.
* 'in's are OR'd together, i.e. only one of them needs to pass.
*/
extern (D) final Statement mergeFrequire(Statement sf, Expressions* params)
{
/* If a base function and its override both have an IN contract, then
* only one of them needs to succeed. This is done by generating:
*
* void derived.in() {
* try {
* base.in();
* }
* catch () {
* ... body of derived.in() ...
* }
* }
*
* So if base.in() doesn't throw, derived.in() need not be executed, and the contract is valid.
* If base.in() throws, then derived.in()'s body is executed.
*/
foreach (fdv; foverrides)
{
/* The semantic pass on the contracts of the overridden functions must
* be completed before code generation occurs.
* https://issues.dlang.org/show_bug.cgi?id=3602
*/
if (fdv.frequires && fdv.semanticRun != PASS.semantic3done)
{
assert(fdv._scope);
Scope* sc = fdv._scope.push();
sc.stc &= ~STC.override_;
fdv.semantic3(sc);
sc.pop();
}
sf = fdv.mergeFrequire(sf, params);
if (!sf || !fdv.fdrequire)
return null;
//printf("fdv.frequire: %s\n", fdv.frequire.toChars());
/* Make the call:
* try { __require(params); }
* catch (Throwable) { frequire; }
*/
params = Expression.arraySyntaxCopy(params);
Expression e = new CallExp(loc, new VarExp(loc, fdv.fdrequire, false), params);
Statement s2 = new ExpStatement(loc, e);
auto c = new Catch(loc, getThrowable(), null, sf);
c.internalCatch = true;
auto catches = new Catches();
catches.push(c);
sf = new TryCatchStatement(loc, s2, catches);
}
return sf;
}
/****************************************************
* Merge into this function the 'in' contracts of all it overrides.
*/
extern (D) final Statement mergeFrequireInclusivePreview(Statement sf, Expressions* params)
{
/* If a base function and its override both have an IN contract, then
* the override in contract must widen the guarantee of the base contract.
* This is checked by generating:
*
* void derived.in() {
* try {
* ... body of derived.in() ...
* }
* catch () {
* // derived in rejected this argument. so parent must also reject it, or we've tightened the contract.
* base.in();
* assert(false, "Logic error: " ~ thr.msg);
* }
*/
foreach (fdv; foverrides)
{
/* The semantic pass on the contracts of the overridden functions must
* be completed before code generation occurs.
* https://issues.dlang.org/show_bug.cgi?id=3602
*/
if (fdv.frequires && fdv.semanticRun != PASS.semantic3done)
{
assert(fdv._scope);
Scope* sc = fdv._scope.push();
sc.stc &= ~STC.override_;
fdv.semantic3(sc);
sc.pop();
}
sf = fdv.mergeFrequireInclusivePreview(sf, params);
if (sf && fdv.fdrequire)
{
const loc = this.fdrequire.loc;
//printf("fdv.frequire: %s\n", fdv.frequire.toChars());
/* Make the call:
* try { frequire; }
* catch (Throwable thr) { __require(params); assert(false, "Logic error: " ~ thr.msg); }
*/
Identifier id = Identifier.generateId("thr");
params = Expression.arraySyntaxCopy(params);
Expression e = new CallExp(loc, new VarExp(loc, fdv.fdrequire, false), params);
Statement s2 = new ExpStatement(loc, e);
// assert(false, ...)
// TODO make this a runtime helper to allow:
// - chaining the original expression
// - nogc concatenation
Expression msg = new StringExp(loc, "Logic error: in-contract was tighter than parent in-contract");
Statement fail = new ExpStatement(loc, new AssertExp(loc, IntegerExp.literal!0, msg));
Statement s3 = new CompoundStatement(loc, s2, fail);
auto c = new Catch(loc, getThrowable(), id, s3);
c.internalCatch = true;
auto catches = new Catches();
catches.push(c);
sf = new TryCatchStatement(loc, sf, catches);
}
else
return null;
}
return sf;
}
/****************************************************
* Determine whether an 'out' contract is declared inside
* the given function or any of its overrides.
* Params:
* fd = the function to search
* Returns:
* true found an 'out' contract
*/
static bool needsFensure(FuncDeclaration fd)
{
if (fd.fensures)
return true;
foreach (fdv; fd.foverrides)
{
if (needsFensure(fdv))
return true;
}
return false;
}
/****************************************************
* Rewrite contracts as statements.
*/
final void buildEnsureRequire()
{
if (frequires)
{
/* in { statements1... }
* in { statements2... }
* ...
* becomes:
* in { { statements1... } { statements2... } ... }
*/
assert(frequires.dim);
auto loc = (*frequires)[0].loc;
auto s = new Statements;
foreach (r; *frequires)
{
s.push(new ScopeStatement(r.loc, r, r.loc));
}
frequire = new CompoundStatement(loc, s);
}
if (fensures)
{
/* out(id1) { statements1... }
* out(id2) { statements2... }
* ...
* becomes:
* out(__result) { { ref id1 = __result; { statements1... } }
* { ref id2 = __result; { statements2... } } ... }
*/
assert(fensures.dim);
auto loc = (*fensures)[0].ensure.loc;
auto s = new Statements;
foreach (r; *fensures)
{
if (r.id && canBuildResultVar())
{
auto rloc = r.ensure.loc;
auto resultId = new IdentifierExp(rloc, Id.result);
auto init = new ExpInitializer(rloc, resultId);
auto stc = STC.ref_ | STC.temp | STC.result;
auto decl = new VarDeclaration(rloc, null, r.id, init, stc);
auto sdecl = new ExpStatement(rloc, decl);
s.push(new ScopeStatement(rloc, new CompoundStatement(rloc, sdecl, r.ensure), rloc));
}
else
{
s.push(r.ensure);
}
}
fensure = new CompoundStatement(loc, s);
}
if (!isVirtual())
return;
/* Rewrite contracts as nested functions, then call them. Doing it as nested
* functions means that overriding functions can call them.
*/
TypeFunction f = cast(TypeFunction) type;
/* Make a copy of the parameters and make them all ref */
static Parameters* toRefCopy(ParameterList parameterList)
{
auto result = new Parameters();
foreach (n, p; parameterList)
{
p = p.syntaxCopy();
if (!p.isLazy())
p.storageClass = (p.storageClass | STC.ref_) & ~STC.out_;
p.defaultArg = null; // won't be the same with ref
result.push(p);
}
return result;
}
if (frequire)
{
/* in { ... }
* becomes:
* void __require(ref params) { ... }
* __require(params);
*/
Loc loc = frequire.loc;
fdrequireParams = new Expressions();
if (parameters)
{
foreach (vd; *parameters)
fdrequireParams.push(new VarExp(loc, vd));
}
auto fo = cast(TypeFunction)(originalType ? originalType : f);
auto fparams = toRefCopy(fo.parameterList);
auto tf = new TypeFunction(ParameterList(fparams), Type.tvoid, LINK.d);
tf.isnothrow = f.isnothrow;
tf.isnogc = f.isnogc;
tf.purity = f.purity;
tf.trust = f.trust;
auto fd = new FuncDeclaration(loc, loc, Id.require, STC.undefined_, tf);
fd.fbody = frequire;
Statement s1 = new ExpStatement(loc, fd);
Expression e = new CallExp(loc, new VarExp(loc, fd, false), fdrequireParams);
Statement s2 = new ExpStatement(loc, e);
frequire = new CompoundStatement(loc, s1, s2);
fdrequire = fd;
}
/* We need to set fdensureParams here and not in the block below to
* have the parameters available when calling a base class ensure(),
* even if this function doesn't have an out contract.
*/
fdensureParams = new Expressions();
if (canBuildResultVar())
fdensureParams.push(new IdentifierExp(loc, Id.result));
if (parameters)
{
foreach (vd; *parameters)
fdensureParams.push(new VarExp(loc, vd));
}
if (fensure)
{
/* out (result) { ... }
* becomes:
* void __ensure(ref tret result, ref params) { ... }
* __ensure(result, params);
*/
Loc loc = fensure.loc;
auto fparams = new Parameters();
if (canBuildResultVar())
{
Parameter p = new Parameter(STC.ref_ | STC.const_, f.nextOf(), Id.result, null, null);
fparams.push(p);
}
auto fo = cast(TypeFunction)(originalType ? originalType : f);
fparams.pushSlice((*toRefCopy(fo.parameterList))[]);
auto tf = new TypeFunction(ParameterList(fparams), Type.tvoid, LINK.d);
tf.isnothrow = f.isnothrow;
tf.isnogc = f.isnogc;
tf.purity = f.purity;
tf.trust = f.trust;
auto fd = new FuncDeclaration(loc, loc, Id.ensure, STC.undefined_, tf);
fd.fbody = fensure;
Statement s1 = new ExpStatement(loc, fd);
Expression e = new CallExp(loc, new VarExp(loc, fd, false), fdensureParams);
Statement s2 = new ExpStatement(loc, e);
fensure = new CompoundStatement(loc, s1, s2);
fdensure = fd;
}
}
/****************************************************
* Merge into this function the 'out' contracts of all it overrides.
* 'out's are AND'd together, i.e. all of them need to pass.
*/
extern (D) final Statement mergeFensure(Statement sf, Identifier oid, Expressions* params)
{
/* Same comments as for mergeFrequire(), except that we take care
* of generating a consistent reference to the 'result' local by
* explicitly passing 'result' to the nested function as a reference
* argument.
* This won't work for the 'this' parameter as it would require changing
* the semantic code for the nested function so that it looks on the parameter
* list for the 'this' pointer, something that would need an unknown amount
* of tweaking of various parts of the compiler that I'd rather leave alone.
*/
foreach (fdv; foverrides)
{
/* The semantic pass on the contracts of the overridden functions must
* be completed before code generation occurs.
* https://issues.dlang.org/show_bug.cgi?id=3602 and
* https://issues.dlang.org/show_bug.cgi?id=5230
*/
if (needsFensure(fdv) && fdv.semanticRun != PASS.semantic3done)
{
assert(fdv._scope);
Scope* sc = fdv._scope.push();
sc.stc &= ~STC.override_;
fdv.semantic3(sc);
sc.pop();
}
sf = fdv.mergeFensure(sf, oid, params);
if (fdv.fdensure)
{
//printf("fdv.fensure: %s\n", fdv.fensure.toChars());
// Make the call: __ensure(result, params)
params = Expression.arraySyntaxCopy(params);
if (canBuildResultVar())
{
Type t1 = fdv.type.nextOf().toBasetype();
Type t2 = this.type.nextOf().toBasetype();
if (t1.isBaseOf(t2, null))
{
/* Making temporary reference variable is necessary
* in covariant return.
* https://issues.dlang.org/show_bug.cgi?id=5204
* https://issues.dlang.org/show_bug.cgi?id=10479
*/
Expression* eresult = &(*params)[0];
auto ei = new ExpInitializer(Loc.initial, *eresult);
auto v = new VarDeclaration(Loc.initial, t1, Identifier.generateId("__covres"), ei);
v.storage_class |= STC.temp;
auto de = new DeclarationExp(Loc.initial, v);
auto ve = new VarExp(Loc.initial, v);
*eresult = new CommaExp(Loc.initial, de, ve);
}
}
Expression e = new CallExp(loc, new VarExp(loc, fdv.fdensure, false), params);
Statement s2 = new ExpStatement(loc, e);
if (sf)
{
sf = new CompoundStatement(sf.loc, s2, sf);
}
else
sf = s2;
}
}
return sf;
}
/*********************************************
* Returns: the function's parameter list, and whether
* it is variadic or not.
*/
final ParameterList getParameterList()
{
if (type)
{
TypeFunction fdtype = type.isTypeFunction();
if (fdtype) // Could also be TypeError
return fdtype.parameterList;
}
return ParameterList(null, VarArg.none);
}
/**********************************
* Generate a FuncDeclaration for a runtime library function.
*/
static FuncDeclaration genCfunc(Parameters* fparams, Type treturn, const(char)* name, StorageClass stc = 0)
{
return genCfunc(fparams, treturn, Identifier.idPool(name, cast(uint)strlen(name)), stc);
}
static FuncDeclaration genCfunc(Parameters* fparams, Type treturn, Identifier id, StorageClass stc = 0)
{
FuncDeclaration fd;
TypeFunction tf;
Dsymbol s;
__gshared DsymbolTable st = null;
//printf("genCfunc(name = '%s')\n", id.toChars());
//printf("treturn\n\t"); treturn.print();
// See if already in table
if (!st)
st = new DsymbolTable();
s = st.lookup(id);
if (s)
{
fd = s.isFuncDeclaration();
assert(fd);
assert(fd.type.nextOf().equals(treturn));
}
else
{
tf = new TypeFunction(ParameterList(fparams), treturn, LINK.c, stc);
fd = new FuncDeclaration(Loc.initial, Loc.initial, id, STC.static_, tf);
fd.visibility = Visibility(Visibility.Kind.public_);
fd._linkage = LINK.c;
st.insert(fd);
}
return fd;
}
/+
+ Checks the parameter and return types iff this is a `main` function.
+
+ The following signatures are allowed for a `D main`:
+ - Either no or a single parameter of type `string[]`
+ - Return type is either `void`, `int` or `noreturn`
+
+ The following signatures are standard C:
+ - `int main()`
+ - `int main(int, char**)`
+
+ This function accepts the following non-standard extensions:
+ - `char** envp` as a third parameter
+ - `void` / `noreturn` as return type
+
+ This function will issue errors for unexpected arguments / return types.
+/
extern (D) final void checkMain()
{
if (ident != Id.main || isMember() || isNested())
return; // Not a main function
TypeFunction tf = type.toTypeFunction();
Type retType = tf.nextOf();
if (!retType)
{
// auto main(), check after semantic
assert(this.inferRetType);
return;
}
/// Checks whether `t` is equivalent to `char**`
/// Ignores qualifiers and treats enums according to their base type
static bool isCharPtrPtr(Type t)
{
auto tp = t.toBasetype().isTypePointer();
if (!tp)
return false;
tp = tp.next.toBasetype().isTypePointer();
if (!tp)
return false;
return tp.next.toBasetype().ty == Tchar;
}
// Neither of these qualifiers is allowed because they affect the ABI
enum invalidSTC = STC.out_ | STC.ref_ | STC.lazy_;
const nparams = tf.parameterList.length;
bool argerr;
const linkage = resolvedLinkage();
if (linkage == LINK.d)
{
if (nparams == 1)
{
auto fparam0 = tf.parameterList[0];
auto t = fparam0.type.toBasetype();
if (t.ty != Tarray ||
t.nextOf().ty != Tarray ||
t.nextOf().nextOf().ty != Tchar ||
fparam0.storageClass & invalidSTC)
{
argerr = true;
}
}
if (tf.parameterList.varargs || nparams >= 2 || argerr)
error("parameter list must be empty or accept one parameter of type `string[]`");
}
else if (linkage == LINK.c)
{
if (nparams == 2 || nparams == 3)
{
// Argument count must be int
auto argCount = tf.parameterList[0];
argerr |= !!(argCount.storageClass & invalidSTC);
argerr |= argCount.type.toBasetype().ty != Tint32;
// Argument pointer must be char**
auto argPtr = tf.parameterList[1];
argerr |= !!(argPtr.storageClass & invalidSTC);
argerr |= !isCharPtrPtr(argPtr.type);
// `char** environ` is a common extension, see J.5.1 of the C standard
if (nparams == 3)
{
auto envPtr = tf.parameterList[2];
argerr |= !!(envPtr.storageClass & invalidSTC);
argerr |= !isCharPtrPtr(envPtr.type);
}
}
else
argerr = nparams != 0;
// Disallow variadic main() - except for K&R declarations in C files.
// E.g. int main(), int main(argc, argv) int argc, char** argc { ... }
if (tf.parameterList.varargs && (!this.isCsymbol() || (!tf.parameterList.hasIdentifierList && nparams)))
argerr |= true;
if (argerr)
{
error("parameters must match one of the following signatures");
loc.errorSupplemental("`main()`");
loc.errorSupplemental("`main(int argc, char** argv)`");
loc.errorSupplemental("`main(int argc, char** argv, char** environ)` [POSIX extension]");
}
}
else
return; // Neither C nor D main, ignore (should probably be an error)
// Allow enums with appropriate base types (same ABI)
retType = retType.toBasetype();
if (retType.ty != Tint32 && retType.ty != Tvoid && retType.ty != Tnoreturn)
error("must return `int`, `void` or `noreturn`, not `%s`", tf.nextOf().toChars());
}
/***********************************************
* Check all return statements for a function to verify that returning
* using NRVO is possible.
*
* Returns:
* `false` if the result cannot be returned by hidden reference.
*/
final bool checkNRVO()
{
if (!isNRVO() || returns is null)
return false;
auto tf = type.toTypeFunction();
if (tf.isref)
return false;
foreach (rs; *returns)
{
if (auto ve = rs.exp.isVarExp())
{
auto v = ve.var.isVarDeclaration();
if (!v || v.isReference())
return false;
else if (nrvo_var is null)
{
// Variables in the data segment (e.g. globals, TLS or not),
// parameters and closure variables cannot be NRVOed.
if (v.isDataseg() || v.isParameter() || v.toParent2() != this)
return false;
if (v.nestedrefs.length && needsClosure())
return false;
// The variable type needs to be equivalent to the return type.
if (!v.type.equivalent(tf.next))
return false;
//printf("Setting nrvo to %s\n", v.toChars());
nrvo_var = v;
}
else if (nrvo_var != v)
return false;
}
else //if (!exp.isLvalue()) // keep NRVO-ability
return false;
}
return true;
}
override final inout(FuncDeclaration) isFuncDeclaration() inout
{
return this;
}
inout(FuncDeclaration) toAliasFunc() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/********************************************************
* Generate Expression to call the invariant.
* Input:
* ad aggregate with the invariant
* vthis variable with 'this'
* Returns:
* void expression that calls the invariant
*/
Expression addInvariant(AggregateDeclaration ad, VarDeclaration vthis)
{
Expression e = null;
// Call invariant directly only if it exists
FuncDeclaration inv = ad.inv;
ClassDeclaration cd = ad.isClassDeclaration();
while (!inv && cd)
{
cd = cd.baseClass;
if (!cd)
break;
inv = cd.inv;
}
if (inv)
{
version (all)
{
// Workaround for https://issues.dlang.org/show_bug.cgi?id=13394
// For the correct mangling,
// run attribute inference on inv if needed.
inv.functionSemantic();
}
//e = new DsymbolExp(Loc.initial, inv);
//e = new CallExp(Loc.initial, e);
//e = e.semantic(sc2);
/* https://issues.dlang.org/show_bug.cgi?id=13113
* Currently virtual invariant calls completely
* bypass attribute enforcement.
* Change the behavior of pre-invariant call by following it.
*/
e = new ThisExp(Loc.initial);
e.type = ad.type.addMod(vthis.type.mod);
e = new DotVarExp(Loc.initial, e, inv, false);
e.type = inv.type;
e = new CallExp(Loc.initial, e);
e.type = Type.tvoid;
}
return e;
}
/***************************************************
* Visit each overloaded function/template in turn, and call dg(s) on it.
* Exit when no more, or dg(s) returns nonzero.
*
* Params:
* fstart = symbol to start from
* dg = the delegate to be called on the overload
* sc = context used to check if symbol is accessible (and therefore visible),
* can be null
*
* Returns:
* ==0 continue
* !=0 done (and the return value from the last dg() call)
*/
extern (D) int overloadApply(Dsymbol fstart, scope int delegate(Dsymbol) dg, Scope* sc = null)
{
Dsymbol next;
for (auto d = fstart; d; d = next)
{
import dmd.access : checkSymbolAccess;
if (auto od = d.isOverDeclaration())
{
/* The scope is needed here to check whether a function in
an overload set was added by means of a private alias (or a
selective import). If the scope where the alias is created
is imported somewhere, the overload set is visible, but the private
alias is not.
*/
if (sc)
{
if (checkSymbolAccess(sc, od))
{
if (int r = overloadApply(od.aliassym, dg, sc))
return r;
}
}
else if (int r = overloadApply(od.aliassym, dg, sc))
return r;
next = od.overnext;
}
else if (auto fa = d.isFuncAliasDeclaration())
{
if (fa.hasOverloads)
{
if (int r = overloadApply(fa.funcalias, dg, sc))
return r;
}
else if (auto fd = fa.toAliasFunc())
{
if (int r = dg(fd))
return r;
}
else
{
d.error("is aliased to a function");
break;
}
next = fa.overnext;
}
else if (auto ad = d.isAliasDeclaration())
{
if (sc)
{
if (checkSymbolAccess(sc, ad))
next = ad.toAlias();
}
else
next = ad.toAlias();
if (next == ad)
break;
if (next == fstart)
break;
}
else if (auto td = d.isTemplateDeclaration())
{
if (int r = dg(td))
return r;
next = td.overnext;
}
else if (auto fd = d.isFuncDeclaration())
{
if (int r = dg(fd))
return r;
next = fd.overnext;
}
else if (auto os = d.isOverloadSet())
{
foreach (ds; os.a)
if (int r = dg(ds))
return r;
}
else
{
d.error("is aliased to a function");
break;
// BUG: should print error message?
}
}
return 0;
}
/**
Checks for mismatching modifiers between `lhsMod` and `rhsMod` and prints the
mismatching modifiers to `buf`.
The modifiers of the `lhsMod` mismatching the ones with the `rhsMod` are printed, i.e.
lhs(shared) vs. rhs() prints "`shared`", wheras lhs() vs rhs(shared) prints "non-shared".
Params:
buf = output buffer to write to
lhsMod = modifier on the left-hand side
lhsMod = modifier on the right-hand side
Returns:
A tuple with `isMutable` and `isNotShared` set
if the `lhsMod` is missing those modifiers (compared to rhs).
*/
auto MODMatchToBuffer(OutBuffer* buf, ubyte lhsMod, ubyte rhsMod)
{
static struct Mismatches
{
bool isNotShared;
bool isMutable;
}
Mismatches mismatches;
bool bothMutable = ((lhsMod & rhsMod) == 0);
bool sharedMismatch = ((lhsMod ^ rhsMod) & MODFlags.shared_) != 0;
bool sharedMismatchOnly = ((lhsMod ^ rhsMod) == MODFlags.shared_);
if (lhsMod & MODFlags.shared_)
buf.writestring("`shared` ");
else if (sharedMismatch && !(lhsMod & MODFlags.immutable_))
{
buf.writestring("non-shared ");
mismatches.isNotShared = true;
}
if (bothMutable && sharedMismatchOnly)
{
}
else if (lhsMod & MODFlags.immutable_)
buf.writestring("`immutable` ");
else if (lhsMod & MODFlags.const_)
buf.writestring("`const` ");
else if (lhsMod & MODFlags.wild)
buf.writestring("`inout` ");
else
{
buf.writestring("mutable ");
mismatches.isMutable = true;
}
return mismatches;
}
///
unittest
{
OutBuffer buf;
auto mismatches = MODMatchToBuffer(&buf, MODFlags.shared_, 0);
assert(buf[] == "`shared` ");
assert(!mismatches.isNotShared);
buf.setsize(0);
mismatches = MODMatchToBuffer(&buf, 0, MODFlags.shared_);
assert(buf[] == "non-shared ");
assert(mismatches.isNotShared);
buf.setsize(0);
mismatches = MODMatchToBuffer(&buf, MODFlags.const_, 0);
assert(buf[] == "`const` ");
assert(!mismatches.isMutable);
buf.setsize(0);
mismatches = MODMatchToBuffer(&buf, 0, MODFlags.const_);
assert(buf[] == "mutable ");
assert(mismatches.isMutable);
}
private const(char)* prependSpace(const(char)* str)
{
if (!str || !*str) return "";
return (" " ~ str.toDString() ~ "\0").ptr;
}
/// Flag used by $(LREF resolveFuncCall).
enum FuncResolveFlag : ubyte
{
standard = 0, /// issue error messages, solve the call.
quiet = 1, /// do not issue error message on no match, just return `null`.
overloadOnly = 2, /// only resolve overloads, i.e. do not issue error on ambiguous
/// matches and need explicit this.
}
/*******************************************
* Given a symbol that could be either a FuncDeclaration or
* a function template, resolve it to a function symbol.
* Params:
* loc = instantiation location
* sc = instantiation scope
* s = instantiation symbol
* tiargs = initial list of template arguments
* tthis = if !NULL, the `this` argument type
* fargs = arguments to function
* flags = see $(LREF FuncResolveFlag).
* Returns:
* if match is found, then function symbol, else null
*/
FuncDeclaration resolveFuncCall(const ref Loc loc, Scope* sc, Dsymbol s,
Objects* tiargs, Type tthis, Expressions* fargs, FuncResolveFlag flags)
{
if (!s)
return null; // no match
version (none)
{
printf("resolveFuncCall('%s')\n", s.toChars());
if (tthis)
printf("\tthis: %s\n", tthis.toChars());
if (fargs)
{
for (size_t i = 0; i < fargs.dim; i++)
{
Expression arg = (*fargs)[i];
assert(arg.type);
printf("\t%s: %s\n", arg.toChars(), arg.type.toChars());
}
}
}
if (tiargs && arrayObjectIsError(tiargs) ||
fargs && arrayObjectIsError(cast(Objects*)fargs))
{
return null;
}
MatchAccumulator m;
functionResolve(m, s, loc, sc, tiargs, tthis, fargs, null);
auto orig_s = s;
if (m.last > MATCH.nomatch && m.lastf)
{
if (m.count == 1) // exactly one match
{
if (!(flags & FuncResolveFlag.quiet))
m.lastf.functionSemantic();
return m.lastf;
}
if ((flags & FuncResolveFlag.overloadOnly) && !tthis && m.lastf.needThis())
{
return m.lastf;
}
}
/* Failed to find a best match.
* Do nothing or print error.
*/
if (m.last == MATCH.nomatch)
{
// error was caused on matched function, not on the matching itself,
// so return the function to produce a better diagnostic
if (m.count == 1)
return m.lastf;
}
// We are done at this point, as the rest of this function generate
// a diagnostic on invalid match
if (flags & FuncResolveFlag.quiet)
return null;
auto fd = s.isFuncDeclaration();
auto od = s.isOverDeclaration();
auto td = s.isTemplateDeclaration();
if (td && td.funcroot)
s = fd = td.funcroot;
OutBuffer tiargsBuf;
arrayObjectsToBuffer(&tiargsBuf, tiargs);
OutBuffer fargsBuf;
fargsBuf.writeByte('(');
argExpTypesToCBuffer(&fargsBuf, fargs);
fargsBuf.writeByte(')');
if (tthis)
tthis.modToBuffer(&fargsBuf);
// The call is ambiguous
if (m.lastf && m.nextf)
{
TypeFunction tf1 = m.lastf.type.toTypeFunction();
TypeFunction tf2 = m.nextf.type.toTypeFunction();
const(char)* lastprms = parametersTypeToChars(tf1.parameterList);
const(char)* nextprms = parametersTypeToChars(tf2.parameterList);
const(char)* mod1 = prependSpace(MODtoChars(tf1.mod));
const(char)* mod2 = prependSpace(MODtoChars(tf2.mod));
.error(loc, "`%s.%s` called with argument types `%s` matches both:\n%s: `%s%s%s`\nand:\n%s: `%s%s%s`",
s.parent.toPrettyChars(), s.ident.toChars(),
fargsBuf.peekChars(),
m.lastf.loc.toChars(), m.lastf.toPrettyChars(), lastprms, mod1,
m.nextf.loc.toChars(), m.nextf.toPrettyChars(), nextprms, mod2);
return null;
}
// no match, generate an error messages
if (!fd)
{
// all of overloads are templates
if (td)
{
.error(loc, "none of the overloads of %s `%s.%s` are callable using argument types `!(%s)%s`",
td.kind(), td.parent.toPrettyChars(), td.ident.toChars(),
tiargsBuf.peekChars(), fargsBuf.peekChars());
if (!global.gag || global.params.showGaggedErrors)
printCandidates(loc, td, sc.isDeprecated());
return null;
}
/* This case used to happen when several ctors are mixed in an agregate.
A (bad) error message is already generated in overloadApply().
see https://issues.dlang.org/show_bug.cgi?id=19729
and https://issues.dlang.org/show_bug.cgi?id=17259
*/
if (!od)
return null;
}
if (od)
{
.error(loc, "none of the overloads of `%s` are callable using argument types `!(%s)%s`",
od.ident.toChars(), tiargsBuf.peekChars(), fargsBuf.peekChars());
return null;
}
// remove when deprecation period of class allocators and deallocators is over
if (fd.isNewDeclaration() && fd.checkDisabled(loc, sc))
return null;
bool hasOverloads = fd.overnext !is null;
auto tf = fd.type.isTypeFunction();
// if type is an error, the original type should be there for better diagnostics
if (!tf)
tf = fd.originalType.toTypeFunction();
if (tthis && !MODimplicitConv(tthis.mod, tf.mod)) // modifier mismatch
{
OutBuffer thisBuf, funcBuf;
MODMatchToBuffer(&thisBuf, tthis.mod, tf.mod);
auto mismatches = MODMatchToBuffer(&funcBuf, tf.mod, tthis.mod);
if (hasOverloads)
{
.error(loc, "none of the overloads of `%s` are callable using a %sobject",
fd.ident.toChars(), thisBuf.peekChars());
if (!global.gag || global.params.showGaggedErrors)
printCandidates(loc, fd, sc.isDeprecated());
return null;
}
const(char)* failMessage;
functionResolve(m, orig_s, loc, sc, tiargs, tthis, fargs, &failMessage);
if (failMessage)
{
.error(loc, "%s `%s%s%s` is not callable using argument types `%s`",
fd.kind(), fd.toPrettyChars(), parametersTypeToChars(tf.parameterList),
tf.modToChars(), fargsBuf.peekChars());
errorSupplemental(loc, failMessage);
return null;
}
.error(loc, "%smethod `%s` is not callable using a %sobject",
funcBuf.peekChars(), fd.toPrettyChars(), thisBuf.peekChars());
if (mismatches.isNotShared)
.errorSupplemental(fd.loc, "Consider adding `shared` here");
else if (mismatches.isMutable)
.errorSupplemental(fd.loc, "Consider adding `const` or `inout` here");
return null;
}
//printf("tf = %s, args = %s\n", tf.deco, (*fargs)[0].type.deco);
if (hasOverloads)
{
.error(loc, "none of the overloads of `%s` are callable using argument types `%s`",
fd.toChars(), fargsBuf.peekChars());
if (!global.gag || global.params.showGaggedErrors)
printCandidates(loc, fd, sc.isDeprecated());
return null;
}
.error(loc, "%s `%s%s%s` is not callable using argument types `%s`",
fd.kind(), fd.toPrettyChars(), parametersTypeToChars(tf.parameterList),
tf.modToChars(), fargsBuf.peekChars());
// re-resolve to check for supplemental message
if (!global.gag || global.params.showGaggedErrors)
{
const(char)* failMessage;
functionResolve(m, orig_s, loc, sc, tiargs, tthis, fargs, &failMessage);
if (failMessage)
errorSupplemental(loc, failMessage);
}
return null;
}
/*******************************************
* Prints template and function overload candidates as supplemental errors.
* Params:
* loc = instantiation location
* declaration = the declaration to print overload candidates for
* showDeprecated = If `false`, `deprecated` function won't be shown
*/
private void printCandidates(Decl)(const ref Loc loc, Decl declaration, bool showDeprecated)
if (is(Decl == TemplateDeclaration) || is(Decl == FuncDeclaration))
{
// max num of overloads to print (-v overrides this).
enum int DisplayLimit = 5;
int displayed;
const(char)* constraintsTip;
// determine if the first candidate was printed
bool printed = false;
overloadApply(declaration, (Dsymbol s)
{
Dsymbol nextOverload;
if (auto fd = s.isFuncDeclaration())
{
// Don't print overloads which have errors.
// Not that if the whole overload set has errors, we'll never reach
// this point so there's no risk of printing no candidate
if (fd.errors || fd.type.ty == Terror)
return 0;
// Don't print disabled functions, or `deprecated` outside of deprecated scope
if (fd.storage_class & STC.disable || (fd.isDeprecated() && !showDeprecated))
return 0;
const single_candidate = fd.overnext is null;
auto tf = cast(TypeFunction) fd.type;
.errorSupplemental(fd.loc,
printed ? " `%s%s`" :
single_candidate ? "Candidate is: `%s%s`" : "Candidates are: `%s%s`",
fd.toPrettyChars(),
parametersTypeToChars(tf.parameterList));
printed = true;
nextOverload = fd.overnext;
}
else if (auto td = s.isTemplateDeclaration())
{
import dmd.staticcond;
const tmsg = td.toCharsNoConstraints();
const cmsg = td.getConstraintEvalError(constraintsTip);
const single_candidate = td.overnext is null;
// add blank space if there are multiple candidates
// the length of the blank space is `strlen("Candidates are: ")`
if (cmsg)
{
.errorSupplemental(td.loc,
printed ? " `%s`\n%s" :
single_candidate ? "Candidate is: `%s`\n%s" : "Candidates are: `%s`\n%s",
tmsg, cmsg);
printed = true;
}
else
{
.errorSupplemental(td.loc,
printed ? " `%s`" :
single_candidate ? "Candidate is: `%s`" : "Candidates are: `%s`",
tmsg);
printed = true;
}
nextOverload = td.overnext;
}
if (global.params.verbose || ++displayed < DisplayLimit)
return 0;
// Too many overloads to sensibly display.
// Just show count of remaining overloads.
int num = 0;
overloadApply(nextOverload, (s) { ++num; return 0; });
if (num > 0)
.errorSupplemental(loc, "... (%d more, -v to show) ...", num);
return 1; // stop iterating
});
// Nothing was displayed, all overloads are either disabled or deprecated
if (!displayed)
.errorSupplemental(loc, "All possible candidates are marked as `deprecated` or `@disable`");
// should be only in verbose mode
if (constraintsTip)
.tip(constraintsTip);
}
/**************************************
* Returns an indirect type one step from t.
*/
Type getIndirection(Type t)
{
t = t.baseElemOf();
if (t.ty == Tarray || t.ty == Tpointer)
return t.nextOf().toBasetype();
if (t.ty == Taarray || t.ty == Tclass)
return t;
if (t.ty == Tstruct)
return t.hasPointers() ? t : null; // TODO
// should consider TypeDelegate?
return null;
}
/**************************************
* Performs type-based alias analysis between a newly created value and a pre-
* existing memory reference:
*
* Assuming that a reference A to a value of type `ta` was available to the code
* that created a reference B to a value of type `tb`, it returns whether B
* might alias memory reachable from A based on the types involved (either
* directly or via any number of indirections in either A or B).
*
* This relation is not symmetric in the two arguments. For example, a
* a `const(int)` reference can point to a pre-existing `int`, but not the other
* way round.
*
* Examples:
*
* ta, tb, result
* `const(int)`, `int`, `false`
* `int`, `const(int)`, `true`
* `int`, `immutable(int)`, `false`
* const(immutable(int)*), immutable(int)*, false // BUG: returns true
*
* Params:
* ta = value type being referred to
* tb = referred to value type that could be constructed from ta
*
* Returns:
* true if reference to `tb` is isolated from reference to `ta`
*/
private bool traverseIndirections(Type ta, Type tb)
{
//printf("traverseIndirections(%s, %s)\n", ta.toChars(), tb.toChars());
static bool traverse(Type ta, Type tb, ref scope AssocArray!(const(char)*, bool) table, bool reversePass)
{
//printf("traverse(%s, %s)\n", ta.toChars(), tb.toChars());
ta = ta.baseElemOf();
tb = tb.baseElemOf();
// First, check if the pointed-to types are convertible to each other such
// that they might alias directly.
static bool mayAliasDirect(Type source, Type target)
{
return
// if source is the same as target or can be const-converted to target
source.constConv(target) != MATCH.nomatch ||
// if target is void and source can be const-converted to target
(target.ty == Tvoid && MODimplicitConv(source.mod, target.mod));
}
if (mayAliasDirect(reversePass ? tb : ta, reversePass ? ta : tb))
{
//printf(" true mayalias %s %s %d\n", ta.toChars(), tb.toChars(), reversePass);
return false;
}
if (ta.nextOf() && ta.nextOf() == tb.nextOf())
{
//printf(" next==next %s %s %d\n", ta.toChars(), tb.toChars(), reversePass);
return true;
}
if (tb.ty == Tclass || tb.ty == Tstruct)
{
/* Traverse the type of each field of the aggregate
*/
bool* found = table.getLvalue(tb.deco);
if (*found == true)
return true; // We have already seen this symbol, break the cycle
else
*found = true;
AggregateDeclaration sym = tb.toDsymbol(null).isAggregateDeclaration();
foreach (v; sym.fields)
{
Type tprmi = v.type.addMod(tb.mod);
//printf("\ttb = %s, tprmi = %s\n", tb.toChars(), tprmi.toChars());
if (!traverse(ta, tprmi, table, reversePass))
return false;
}
}
else if (tb.ty == Tarray || tb.ty == Taarray || tb.ty == Tpointer)
{
Type tind = tb.nextOf();
if (!traverse(ta, tind, table, reversePass))
return false;
}
else if (tb.hasPointers())
{
// BUG: consider the context pointer of delegate types
return false;
}
// Still no match, so try breaking up ta if we have not done so yet.
if (!reversePass)
{
scope newTable = AssocArray!(const(char)*, bool)();
return traverse(tb, ta, newTable, true);
}
return true;
}
// To handle arbitrary levels of indirections in both parameters, we
// recursively descend into aggregate members/levels of indirection in both
// `ta` and `tb` while avoiding cycles. Start with the original types.
scope table = AssocArray!(const(char)*, bool)();
const result = traverse(ta, tb, table, false);
//printf(" returns %d\n", result);
return result;
}
/* For all functions between outerFunc and f, mark them as needing
* a closure.
*/
private void markAsNeedingClosure(Dsymbol f, FuncDeclaration outerFunc)
{
for (Dsymbol sx = f; sx && sx != outerFunc; sx = sx.toParentP(outerFunc))
{
FuncDeclaration fy = sx.isFuncDeclaration();
if (fy && fy.closureVars.dim)
{
/* fy needs a closure if it has closureVars[],
* because the frame pointer in the closure will be accessed.
*/
fy.requiresClosure = true;
}
}
}
/********
* Given a nested function f inside a function outerFunc, check
* if any sibling callers of f have escaped. If so, mark
* all the enclosing functions as needing closures.
* This is recursive: we need to check the callers of our siblings.
* Note that nested functions can only call lexically earlier nested
* functions, so loops are impossible.
* Params:
* f = inner function (nested within outerFunc)
* outerFunc = outer function
* p = for internal recursion use
* Returns:
* true if any closures were needed
*/
private bool checkEscapingSiblings(FuncDeclaration f, FuncDeclaration outerFunc, void* p = null)
{
static struct PrevSibling
{
PrevSibling* p;
FuncDeclaration f;
}
PrevSibling ps;
ps.p = cast(PrevSibling*)p;
ps.f = f;
//printf("checkEscapingSiblings(f = %s, outerfunc = %s)\n", f.toChars(), outerFunc.toChars());
bool bAnyClosures = false;
for (size_t i = 0; i < f.siblingCallers.dim; ++i)
{
FuncDeclaration g = f.siblingCallers[i];
if (g.isThis() || g.tookAddressOf)
{
markAsNeedingClosure(g, outerFunc);
bAnyClosures = true;
}
for (auto parent = g.toParentP(outerFunc); parent && parent !is outerFunc; parent = parent.toParentP(outerFunc))
{
// A parent of the sibling had its address taken.
// Assume escaping of parent affects its children, so needs propagating.
// see https://issues.dlang.org/show_bug.cgi?id=19679
FuncDeclaration parentFunc = parent.isFuncDeclaration;
if (parentFunc && parentFunc.tookAddressOf)
{
markAsNeedingClosure(parentFunc, outerFunc);
bAnyClosures = true;
}
}
PrevSibling* prev = cast(PrevSibling*)p;
while (1)
{
if (!prev)
{
bAnyClosures |= checkEscapingSiblings(g, outerFunc, &ps);
break;
}
if (prev.f == g)
break;
prev = prev.p;
}
}
//printf("\t%d\n", bAnyClosures);
return bAnyClosures;
}
/***********************************************************
* Used as a way to import a set of functions from another scope into this one.
*/
extern (C++) final class FuncAliasDeclaration : FuncDeclaration
{
FuncDeclaration funcalias;
bool hasOverloads;
extern (D) this(Identifier ident, FuncDeclaration funcalias, bool hasOverloads = true)
{
super(funcalias.loc, funcalias.endloc, ident, funcalias.storage_class, funcalias.type);
assert(funcalias != this);
this.funcalias = funcalias;
this.hasOverloads = hasOverloads;
if (hasOverloads)
{
if (FuncAliasDeclaration fad = funcalias.isFuncAliasDeclaration())
this.hasOverloads = fad.hasOverloads;
}
else
{
// for internal use
assert(!funcalias.isFuncAliasDeclaration());
this.hasOverloads = false;
}
userAttribDecl = funcalias.userAttribDecl;
}
override inout(FuncAliasDeclaration) isFuncAliasDeclaration() inout
{
return this;
}
override const(char)* kind() const
{
return "function alias";
}
override inout(FuncDeclaration) toAliasFunc() inout
{
return funcalias.toAliasFunc();
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class FuncLiteralDeclaration : FuncDeclaration
{
TOK tok; // TOK.function_ or TOK.delegate_
Type treq; // target of return type inference
// backend
bool deferToObj;
extern (D) this(const ref Loc loc, const ref Loc endloc, Type type, TOK tok, ForeachStatement fes, Identifier id = null)
{
super(loc, endloc, null, STC.undefined_, type);
this.ident = id ? id : Id.empty;
this.tok = tok;
this.fes = fes;
// Always infer scope for function literals
// See https://issues.dlang.org/show_bug.cgi?id=20362
this.flags |= FUNCFLAG.inferScope;
//printf("FuncLiteralDeclaration() id = '%s', type = '%s'\n", this.ident.toChars(), type.toChars());
}
override FuncLiteralDeclaration syntaxCopy(Dsymbol s)
{
//printf("FuncLiteralDeclaration::syntaxCopy('%s')\n", toChars());
assert(!s);
auto f = new FuncLiteralDeclaration(loc, endloc, type.syntaxCopy(), tok, fes, ident);
f.treq = treq; // don't need to copy
FuncDeclaration.syntaxCopy(f);
return f;
}
override bool isNested() const
{
//printf("FuncLiteralDeclaration::isNested() '%s'\n", toChars());
return (tok != TOK.function_) && !isThis();
}
override inout(AggregateDeclaration) isThis() inout
{
return tok == TOK.delegate_ ? super.isThis() : null;
}
override bool isVirtual() const
{
return false;
}
override bool addPreInvariant()
{
return false;
}
override bool addPostInvariant()
{
return false;
}
/*******************************
* Modify all expression type of return statements to tret.
*
* On function literals, return type may be modified based on the context type
* after its semantic3 is done, in FuncExp::implicitCastTo.
*
* A function() dg = (){ return new B(); } // OK if is(B : A) == true
*
* If B to A conversion is convariant that requires offseet adjusting,
* all return statements should be adjusted to return expressions typed A.
*/
void modifyReturns(Scope* sc, Type tret)
{
import dmd.statement_rewrite_walker;
extern (C++) final class RetWalker : StatementRewriteWalker
{
alias visit = typeof(super).visit;
public:
Scope* sc;
Type tret;
FuncLiteralDeclaration fld;
override void visit(ReturnStatement s)
{
Expression exp = s.exp;
if (exp && !exp.type.equals(tret))
{
s.exp = exp.castTo(sc, tret);
}
}
}
if (semanticRun < PASS.semantic3done)
return;
if (fes)
return;
scope RetWalker w = new RetWalker();
w.sc = sc;
w.tret = tret;
w.fld = this;
fbody.accept(w);
// Also update the inferred function type to match the new return type.
// This is required so the code generator does not try to cast the
// modified returns back to the original type.
if (inferRetType && type.nextOf() != tret)
type.toTypeFunction().next = tret;
}
override inout(FuncLiteralDeclaration) isFuncLiteralDeclaration() inout
{
return this;
}
override const(char)* kind() const
{
// GCC requires the (char*) casts
return (tok != TOK.function_) ? "delegate" : "function";
}
override const(char)* toPrettyChars(bool QualifyTypes = false)
{
if (parent)
{
TemplateInstance ti = parent.isTemplateInstance();
if (ti)
return ti.tempdecl.toPrettyChars(QualifyTypes);
}
return Dsymbol.toPrettyChars(QualifyTypes);
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class CtorDeclaration : FuncDeclaration
{
bool isCpCtor;
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc, Type type, bool isCpCtor = false)
{
super(loc, endloc, Id.ctor, stc, type);
this.isCpCtor = isCpCtor;
//printf("CtorDeclaration(loc = %s) %s\n", loc.toChars(), toChars());
}
override CtorDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto f = new CtorDeclaration(loc, endloc, storage_class, type.syntaxCopy());
FuncDeclaration.syntaxCopy(f);
return f;
}
override const(char)* kind() const
{
return isCpCtor ? "copy constructor" : "constructor";
}
override const(char)* toChars() const
{
return "this";
}
override bool isVirtual() const
{
return false;
}
override bool addPreInvariant()
{
return false;
}
override bool addPostInvariant()
{
return (isThis() && vthis && global.params.useInvariants == CHECKENABLE.on);
}
override inout(CtorDeclaration) isCtorDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class PostBlitDeclaration : FuncDeclaration
{
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc, Identifier id)
{
super(loc, endloc, id, stc, null);
}
override PostBlitDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto dd = new PostBlitDeclaration(loc, endloc, storage_class, ident);
FuncDeclaration.syntaxCopy(dd);
return dd;
}
override bool isVirtual() const
{
return false;
}
override bool addPreInvariant()
{
return false;
}
override bool addPostInvariant()
{
return (isThis() && vthis && global.params.useInvariants == CHECKENABLE.on);
}
override bool overloadInsert(Dsymbol s)
{
return false; // cannot overload postblits
}
override inout(PostBlitDeclaration) isPostBlitDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class DtorDeclaration : FuncDeclaration
{
extern (D) this(const ref Loc loc, const ref Loc endloc)
{
super(loc, endloc, Id.dtor, STC.undefined_, null);
}
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc, Identifier id)
{
super(loc, endloc, id, stc, null);
}
override DtorDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto dd = new DtorDeclaration(loc, endloc, storage_class, ident);
FuncDeclaration.syntaxCopy(dd);
return dd;
}
override const(char)* kind() const
{
return "destructor";
}
override const(char)* toChars() const
{
return "~this";
}
override bool isVirtual() const
{
// D dtor's don't get put into the vtbl[]
// this is a hack so that extern(C++) destructors report as virtual, which are manually added to the vtable
return vtblIndex != -1;
}
override bool addPreInvariant()
{
return (isThis() && vthis && global.params.useInvariants == CHECKENABLE.on);
}
override bool addPostInvariant()
{
return false;
}
override bool overloadInsert(Dsymbol s)
{
return false; // cannot overload destructors
}
override inout(DtorDeclaration) isDtorDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) class StaticCtorDeclaration : FuncDeclaration
{
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc)
{
super(loc, endloc, Identifier.generateIdWithLoc("_staticCtor", loc), STC.static_ | stc, null);
}
extern (D) this(const ref Loc loc, const ref Loc endloc, string name, StorageClass stc)
{
super(loc, endloc, Identifier.generateIdWithLoc(name, loc), STC.static_ | stc, null);
}
override StaticCtorDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto scd = new StaticCtorDeclaration(loc, endloc, storage_class);
FuncDeclaration.syntaxCopy(scd);
return scd;
}
override final inout(AggregateDeclaration) isThis() inout @nogc nothrow pure @safe
{
return null;
}
override final bool isVirtual() const @nogc nothrow pure @safe
{
return false;
}
override final bool addPreInvariant() @nogc nothrow pure @safe
{
return false;
}
override final bool addPostInvariant() @nogc nothrow pure @safe
{
return false;
}
override final bool hasStaticCtorOrDtor() @nogc nothrow pure @safe
{
return true;
}
override final inout(StaticCtorDeclaration) isStaticCtorDeclaration() inout @nogc nothrow pure @safe
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class SharedStaticCtorDeclaration : StaticCtorDeclaration
{
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc)
{
super(loc, endloc, "_sharedStaticCtor", stc);
}
override SharedStaticCtorDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto scd = new SharedStaticCtorDeclaration(loc, endloc, storage_class);
FuncDeclaration.syntaxCopy(scd);
return scd;
}
override inout(SharedStaticCtorDeclaration) isSharedStaticCtorDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) class StaticDtorDeclaration : FuncDeclaration
{
VarDeclaration vgate; // 'gate' variable
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc)
{
super(loc, endloc, Identifier.generateIdWithLoc("_staticDtor", loc), STC.static_ | stc, null);
}
extern (D) this(const ref Loc loc, const ref Loc endloc, string name, StorageClass stc)
{
super(loc, endloc, Identifier.generateIdWithLoc(name, loc), STC.static_ | stc, null);
}
override StaticDtorDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto sdd = new StaticDtorDeclaration(loc, endloc, storage_class);
FuncDeclaration.syntaxCopy(sdd);
return sdd;
}
override final inout(AggregateDeclaration) isThis() inout
{
return null;
}
override final bool isVirtual() const
{
return false;
}
override final bool hasStaticCtorOrDtor()
{
return true;
}
override final bool addPreInvariant()
{
return false;
}
override final bool addPostInvariant()
{
return false;
}
override final inout(StaticDtorDeclaration) isStaticDtorDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class SharedStaticDtorDeclaration : StaticDtorDeclaration
{
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc)
{
super(loc, endloc, "_sharedStaticDtor", stc);
}
override SharedStaticDtorDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto sdd = new SharedStaticDtorDeclaration(loc, endloc, storage_class);
FuncDeclaration.syntaxCopy(sdd);
return sdd;
}
override inout(SharedStaticDtorDeclaration) isSharedStaticDtorDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class InvariantDeclaration : FuncDeclaration
{
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc, Identifier id, Statement fbody)
{
// Make a unique invariant for now; we'll fix it up as we add it to the aggregate invariant list.
super(loc, endloc, id ? id : Identifier.generateId("__invariant"), stc, null);
this.fbody = fbody;
}
override InvariantDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto id = new InvariantDeclaration(loc, endloc, storage_class, null, null);
FuncDeclaration.syntaxCopy(id);
return id;
}
override bool isVirtual() const
{
return false;
}
override bool addPreInvariant()
{
return false;
}
override bool addPostInvariant()
{
return false;
}
override inout(InvariantDeclaration) isInvariantDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
extern (D) void fixupInvariantIdent(size_t offset)
{
OutBuffer idBuf;
idBuf.writestring("__invariant");
idBuf.print(offset);
ident = Identifier.idPool(idBuf[]);
}
}
/***********************************************************
*/
extern (C++) final class UnitTestDeclaration : FuncDeclaration
{
char* codedoc; // for documented unittest
// toObjFile() these nested functions after this one
FuncDeclarations deferredNested;
extern (D) this(const ref Loc loc, const ref Loc endloc, StorageClass stc, char* codedoc)
{
super(loc, endloc, Identifier.generateIdWithLoc("__unittest", loc), stc, null);
this.codedoc = codedoc;
}
override UnitTestDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto utd = new UnitTestDeclaration(loc, endloc, storage_class, codedoc);
FuncDeclaration.syntaxCopy(utd);
return utd;
}
override inout(AggregateDeclaration) isThis() inout
{
return null;
}
override bool isVirtual() const
{
return false;
}
override bool addPreInvariant()
{
return false;
}
override bool addPostInvariant()
{
return false;
}
override inout(UnitTestDeclaration) isUnitTestDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/***********************************************************
*/
extern (C++) final class NewDeclaration : FuncDeclaration
{
extern (D) this(const ref Loc loc, StorageClass stc)
{
super(loc, Loc.initial, Id.classNew, STC.static_ | stc, null);
}
override NewDeclaration syntaxCopy(Dsymbol s)
{
assert(!s);
auto f = new NewDeclaration(loc, storage_class);
FuncDeclaration.syntaxCopy(f);
return f;
}
override const(char)* kind() const
{
return "allocator";
}
override bool isVirtual() const
{
return false;
}
override bool addPreInvariant()
{
return false;
}
override bool addPostInvariant()
{
return false;
}
override inout(NewDeclaration) isNewDeclaration() inout
{
return this;
}
override void accept(Visitor v)
{
v.visit(this);
}
}
/**************************************
* A statement / expression in this scope is not `@safe`,
* so mark the enclosing function as `@system`
*
* Params:
* sc = scope that the unsafe statement / expression is in
* gag = surpress error message (used in escape.d)
* loc = location of error
* fmt = printf-style format string
* arg0 = (optional) argument for first %s format specifier
* arg1 = (optional) argument for second %s format specifier
* arg2 = (optional) argument for third %s format specifier
* Returns: whether there's a safe error
*/
bool setUnsafe(Scope* sc,
bool gag = false, Loc loc = Loc.init, const(char)* fmt = null,
RootObject arg0 = null, RootObject arg1 = null, RootObject arg2 = null)
{
// TODO:
// For @system variables, unsafe initializers at global scope should mark
// the variable @system, see https://dlang.org/dips/1035
if (!sc.func)
return false;
if (sc.intypeof)
return false; // typeof(cast(int*)0) is safe
if (sc.flags & SCOPE.debug_) // debug {} scopes are permissive
return false;
if (sc.flags & SCOPE.compile) // __traits(compiles, x)
{
if (sc.func.isSafeBypassingInference())
{
// Message wil be gagged, but still call error() to update global.errors and for
// -verrors=spec
.error(loc, fmt, arg0 ? arg0.toChars() : "", arg1 ? arg1.toChars() : "", arg2 ? arg2.toChars() : "");
return true;
}
return false;
}
return sc.func.setUnsafe(gag, loc, fmt, arg0, arg1, arg2);
}
/// Stores a reason why a function failed to infer a function attribute like `@safe` or `pure`
///
/// Has two modes:
/// - a regular safety error, stored in (fmtStr, arg0, arg1)
/// - a call to a function without the attribute, which is a special case, because in that case,
/// that function might recursively also have a `AttributeViolation`. This way, in case
/// of a big call stack, the error can go down all the way to the root cause.
/// The `FunctionDeclaration` is then stored in `arg0` and `fmtStr` must be `null`.
struct AttributeViolation
{
/// location of error
Loc loc = Loc.init;
/// printf-style format string
const(char)* fmtStr = null;
/// Arguments for up to two `%s` format specifiers in format string
RootObject arg0 = null;
/// ditto
RootObject arg1 = null;
/// ditto
RootObject arg2 = null;
}
/// Print the reason why `fd` was inferred `@system` as a supplemental error
/// Params:
/// fd = function to check
/// maxDepth = up to how many functions deep to report errors
/// deprecation = print deprecations instead of errors
void errorSupplementalInferredSafety(FuncDeclaration fd, int maxDepth, bool deprecation)
{
auto errorFunc = deprecation ? &deprecationSupplemental : &errorSupplemental;
if (auto s = fd.safetyViolation)
{
if (s.fmtStr)
{
errorFunc(s.loc, deprecation ?
"which would be `@system` because of:" :
"which was inferred `@system` because of:");
errorFunc(s.loc, s.fmtStr,
s.arg0 ? s.arg0.toChars() : "", s.arg1 ? s.arg1.toChars() : "", s.arg2 ? s.arg2.toChars() : "");
}
else if (s.arg0.dyncast() == DYNCAST.dsymbol)
{
if (FuncDeclaration fd2 = (cast(Dsymbol) s.arg0).isFuncDeclaration())
{
if (maxDepth > 0)
{
errorFunc(s.loc, "which calls `%s`", fd2.toPrettyChars());
errorSupplementalInferredSafety(fd2, maxDepth - 1, deprecation);
}
}
}
}
}
|