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
|
//===--- DynamicCast.cpp - Swift Language Dynamic Casting Support ---------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2020 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// Implementations of the dynamic cast runtime functions.
//
//===----------------------------------------------------------------------===//
#include "../CompatibilityOverride/CompatibilityOverride.h"
#include "ErrorObject.h"
#include "Private.h"
#include "SwiftHashableSupport.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/Basic/Lazy.h"
#include "swift/Runtime/Bincompat.h"
#include "swift/Runtime/Casting.h"
#include "swift/Runtime/Config.h"
#include "swift/Runtime/ExistentialContainer.h"
#include "swift/Runtime/HeapObject.h"
#if SWIFT_OBJC_INTEROP
#include "swift/Runtime/ObjCBridge.h"
#include "SwiftObject.h"
#include "SwiftValue.h"
#endif
using namespace swift;
using namespace hashable_support;
//
// The top-level driver code directly handles the most general cases
// (identity casts, _ObjectiveCBridgeable, _SwiftValue boxing) and
// recursively unwraps source and/or destination as appropriate.
// It calls "tryCastToXyz" functions to perform tailored operations
// for a particular destination type.
//
// For each kind of destination, there is a "tryCastToXyz" that
// accepts a source value and attempts to fit it into a destination
// storage location. This function should assume that:
// * The source and destination types are _not_ identical.
// * The destination is of the expected type.
// * The source is already fully unwrapped. If the source is an
// Existential or Optional that you cannot handle directly, do _not_
// try to unwrap it. Just return failure and you will get called
// again with the unwrapped source.
//
// Each such function accepts the following arguments:
// * Destination location and type
// * Source value address and type
// * References to the types that will be used to report failure.
// The function can update these with specific failing types
// to improve the reported failure.
// * Bool indicating whether the compiler has asked us to "take" the
// value instead of copying.
// * Bool indicating whether it's okay to do type checks lazily on later
// access (this is permitted only for unconditional casts that will
// abort the program on failure anyway).
//
// The return value is one of the following:
// * Failure. In this case, the tryCastFunction should do nothing; your
// caller will either try another strategy or report the failure and
// do any necessary cleanup.
// * Success via "copy". You successfully copied the source value.
// * Success via "take". If "take" was requested and you can do so cheaply,
// perform the take and return SuccessViaTake. If "take" is not cheap, you
// should copy and return SuccessViaCopy. Top-level code will detect this
// and take care of destroying the source for you.
//
enum class DynamicCastResult {
Failure, /// The cast attempt "failed" (did nothing).
SuccessViaCopy, /// Cast succeeded, source is still valid.
SuccessViaTake, /// Cast succeeded, source is invalid
};
static bool isSuccess(DynamicCastResult result) {
return result != DynamicCastResult::Failure;
}
// All of our `tryCastXyz` functions have the following signature.
typedef DynamicCastResult (tryCastFunctionType)(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks
);
// Forward-declare the main top-level `tryCast()` function
static tryCastFunctionType tryCast;
/// Nominal type descriptor for Swift.AnyHashable
extern "C" const StructDescriptor STRUCT_TYPE_DESCR_SYM(s11AnyHashable);
/// Nominal type descriptor for Swift.__SwiftValue
//extern "C" const StructDescriptor STRUCT_TYPE_DESCR_SYM(s12__SwiftValue);
/// Nominal type descriptor for Swift.Array.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(Sa);
/// Nominal type descriptor for Swift.Dictionary.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(SD);
/// Nominal type descriptor for Swift.Set.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(Sh);
/// Nominal type descriptor for Swift.String.
extern "C" const StructDescriptor NOMINAL_TYPE_DESCR_SYM(SS);
/// This issues a fatal error or warning if the srcValue contains a null object
/// reference. It is used when the srcType is a non-nullable reference type, in
/// which case it is dangerous to continue with a null reference. The null
/// reference is returned if we're operating in backwards-compatibility mode, so
/// callers still have to check for null.
static HeapObject * getNonNullSrcObject(OpaqueValue *srcValue,
const Metadata *srcType,
const Metadata *destType) {
auto object = *reinterpret_cast<HeapObject **>(srcValue);
if (LLVM_LIKELY(object != nullptr)) {
return object;
}
std::string srcTypeName = nameForMetadata(srcType);
std::string destTypeName = nameForMetadata(destType);
const char * const msg = "Found a null pointer in a value of type '%s' (%p)."
" Non-Optional values are not allowed to hold null pointers."
" (Detected while casting to '%s' (%p))%s\n";
if (runtime::bincompat::useLegacyPermissiveObjCNullSemanticsInCasting()) {
// In backwards compatibility mode, this code will warn and return the null
// reference anyway: If you examine the calls to the function, you'll see
// that most callers fail the cast in that case, but a few casts (e.g., with
// Obj-C or CF destination type) sill succeed in that case. This is
// dangerous, but necessary for compatibility.
swift::warning(/* flags = */ 0, msg,
srcTypeName.c_str(), srcType,
destTypeName.c_str(), destType,
": Continuing with null object, but expect problems later.");
} else {
// By default, Swift 5.4 and later issue a fatal error.
swift::fatalError(/* flags = */ 0, msg,
srcTypeName.c_str(), srcType,
destTypeName.c_str(), destType,
"");
}
return object;
}
/******************************************************************************/
/******************************* Bridge Helpers *******************************/
/******************************************************************************/
#define _bridgeAnythingToObjectiveC \
MANGLE_SYM(s27_bridgeAnythingToObjectiveCyyXlxlF)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_API
HeapObject *_bridgeAnythingToObjectiveC(
OpaqueValue *src, const Metadata *srcType);
#if SWIFT_OBJC_INTEROP
SWIFT_RUNTIME_EXPORT
id swift_dynamicCastMetatypeToObjectConditional(const Metadata *metatype);
#endif
// protocol _ObjectiveCBridgeable {
struct _ObjectiveCBridgeableWitnessTable : WitnessTable {
#define _protocolWitnessSignedPointer(n) \
__ptrauth_swift_protocol_witness_function_pointer(SpecialPointerAuthDiscriminators::n##Discriminator) n
static_assert(WitnessTableFirstRequirementOffset == 1,
"Witness table layout changed");
// associatedtype _ObjectiveCType : class
void *_ObjectiveCType;
// func _bridgeToObjectiveC() -> _ObjectiveCType
SWIFT_CC(swift)
HeapObject *(*_protocolWitnessSignedPointer(bridgeToObjectiveC))(
SWIFT_CONTEXT OpaqueValue *self, const Metadata *Self,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// class func _forceBridgeFromObjectiveC(x: _ObjectiveCType,
// inout result: Self?)
SWIFT_CC(swift)
void (*_protocolWitnessSignedPointer(forceBridgeFromObjectiveC))(
HeapObject *sourceValue,
OpaqueValue *result,
SWIFT_CONTEXT const Metadata *self,
const Metadata *selfType,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
// class func _conditionallyBridgeFromObjectiveC(x: _ObjectiveCType,
// inout result: Self?) -> Bool
SWIFT_CC(swift)
bool (*_protocolWitnessSignedPointer(conditionallyBridgeFromObjectiveC))(
HeapObject *sourceValue,
OpaqueValue *result,
SWIFT_CONTEXT const Metadata *self,
const Metadata *selfType,
const _ObjectiveCBridgeableWitnessTable *witnessTable);
};
// }
extern "C" const ProtocolDescriptor
PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable);
static const _ObjectiveCBridgeableWitnessTable *
findBridgeWitness(const Metadata *T) {
auto w = swift_conformsToProtocolCommon(
T, &PROTOCOL_DESCR_SYM(s21_ObjectiveCBridgeable));
return reinterpret_cast<const _ObjectiveCBridgeableWitnessTable *>(w);
}
/// Retrieve the bridged Objective-C type for the given type that
/// conforms to \c _ObjectiveCBridgeable.
MetadataResponse
_getBridgedObjectiveCType(
MetadataRequest request,
const Metadata *conformingType,
const _ObjectiveCBridgeableWitnessTable *wtable)
{
// FIXME: Can we directly reference the descriptor somehow?
const ProtocolConformanceDescriptor *conformance = wtable->getDescription();
const ProtocolDescriptor *protocol = conformance->getProtocol();
auto assocTypeRequirement = protocol->getRequirements().begin();
assert(assocTypeRequirement->Flags.getKind() ==
ProtocolRequirementFlags::Kind::AssociatedTypeAccessFunction);
auto mutableWTable = (WitnessTable *)wtable;
return swift_getAssociatedTypeWitness(
request, mutableWTable, conformingType,
protocol->getRequirementBaseDescriptor(),
assocTypeRequirement);
}
/// Dynamic cast from a class type to a value type that conforms to the
/// _ObjectiveCBridgeable, first by dynamic casting the object to the
/// class to which the value type is bridged, and then bridging
/// from that object to the value type via the witness table.
///
/// Caveat: Despite the name, this is also used to bridge pure Swift
/// classes to Swift value types even when Obj-C is not being used.
static DynamicCastResult
_tryCastFromClassToObjCBridgeable(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType, void *srcObject,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks,
const _ObjectiveCBridgeableWitnessTable *destBridgeWitness,
const Metadata *targetBridgeClass)
{
// 2. Allocate a T? to receive the bridge result.
// The extra byte is for the tag.
auto targetSize = destType->getValueWitnesses()->getSize() + 1;
auto targetAlignMask = destType->getValueWitnesses()->getAlignmentMask();
// Object that frees a buffer when it goes out of scope.
struct FreeBuffer {
void *Buffer = nullptr;
size_t size, alignMask;
FreeBuffer(size_t size, size_t alignMask) :
size(size), alignMask(alignMask) {}
~FreeBuffer() {
if (Buffer)
swift_slowDealloc(Buffer, size, alignMask);
}
} freeBuffer{targetSize, targetAlignMask};
// The extra byte is for the tag on the T?
const std::size_t inlineValueSize = 3 * sizeof(void*);
alignas(MaximumAlignment) char inlineBuffer[inlineValueSize + 1];
void *optDestBuffer;
if (destType->getValueWitnesses()->getStride() <= inlineValueSize) {
// Use the inline buffer.
optDestBuffer = inlineBuffer;
} else {
// Allocate a buffer.
optDestBuffer = swift_slowAlloc(targetSize, targetAlignMask);
freeBuffer.Buffer = optDestBuffer;
}
// Initialize the buffer as an empty optional.
destType->vw_storeEnumTagSinglePayload((OpaqueValue *)optDestBuffer,
1, 1);
// 3. Bridge into the T? (Effectively a copy operation.)
bool success;
if (mayDeferChecks) {
destBridgeWitness->forceBridgeFromObjectiveC(
(HeapObject *)srcObject, (OpaqueValue *)optDestBuffer,
destType, destType, destBridgeWitness);
success = true;
} else {
success = destBridgeWitness->conditionallyBridgeFromObjectiveC(
(HeapObject *)srcObject, (OpaqueValue *)optDestBuffer,
destType, destType, destBridgeWitness);
}
// If we succeeded, then take the value from the temp buffer.
if (success) {
destType->vw_initializeWithTake(destLocation, (OpaqueValue *)optDestBuffer);
// Bridge above is effectively a copy, so overall we're a copy.
return DynamicCastResult::SuccessViaCopy;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastFromClassToObjCBridgeable(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
// We need the _ObjectiveCBridgeable conformance for the target
auto destBridgeWitness = findBridgeWitness(destType);
if (destBridgeWitness == nullptr) {
return DynamicCastResult::Failure;
}
// 1. Soundness check whether the source object can cast to the
// type expected by the target.
auto targetBridgedClass =
_getBridgedObjectiveCType(MetadataState::Complete, destType,
destBridgeWitness).Value;
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// Note: srcObject can be null here in compatibility mode
if (nullptr == srcObject
|| nullptr == swift_dynamicCastUnknownClass(srcObject, targetBridgedClass)) {
destFailureType = targetBridgedClass;
return DynamicCastResult::Failure;
}
return _tryCastFromClassToObjCBridgeable(
destLocation, destType,
srcValue, srcType, srcObject,
destFailureType, srcFailureType,
takeOnSuccess, mayDeferChecks,
destBridgeWitness, targetBridgedClass);
}
/// Dynamic cast from a value type that conforms to the
/// _ObjectiveCBridgeable protocol to a class type, first by bridging
/// the value to its Objective-C object representation and then by
/// dynamic casting that object to the resulting target type.
///
/// Caveat: Despite the name, this is also used to bridge Swift value types
/// to Swift classes even when Obj-C is not being used.
static DynamicCastResult
tryCastFromObjCBridgeableToClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
auto srcBridgeWitness = findBridgeWitness(srcType);
if (srcBridgeWitness == nullptr) {
return DynamicCastResult::Failure;
}
// Bridge the source value to an object.
auto srcBridgedObject =
srcBridgeWitness->bridgeToObjectiveC(srcValue, srcType, srcBridgeWitness);
// Dynamic cast the object to the resulting class type.
if (auto cast = swift_dynamicCastUnknownClass(srcBridgedObject, destType)) {
*reinterpret_cast<const void **>(destLocation) = cast;
return DynamicCastResult::SuccessViaCopy;
} else {
// We don't need the object anymore.
swift_unknownObjectRelease(srcBridgedObject);
return DynamicCastResult::Failure;
}
}
/******************************************************************************/
/****************************** SwiftValue Boxing *****************************/
/******************************************************************************/
#if !SWIFT_OBJC_INTEROP // __SwiftValue is a native class
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_unboxFromSwiftValueWithType(OpaqueValue *source,
OpaqueValue *result,
const Metadata *destinationType);
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool swift_swiftValueConformsTo(const Metadata *, const Metadata *);
#endif
#if SWIFT_OBJC_INTEROP
// Try unwrapping a source holding an Obj-C SwiftValue container and
// recursively casting the contents.
static DynamicCastResult
tryCastUnwrappingObjCSwiftValueSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
id srcObject;
memcpy(&srcObject, srcValue, sizeof(id));
auto srcSwiftValue = getAsSwiftValue(srcObject);
if (srcSwiftValue == nullptr) {
return DynamicCastResult::Failure;
}
const Metadata *srcInnerType;
const OpaqueValue *srcInnerValue;
std::tie(srcInnerType, srcInnerValue)
= getValueFromSwiftValue(srcSwiftValue);
// Note: We never `take` the contents from a SwiftValue box as
// it might have other references. Instead, let our caller
// destroy the reference if necessary.
return tryCast(
destLocation, destType,
const_cast<OpaqueValue *>(srcInnerValue), srcInnerType,
destFailureType, srcFailureType,
/*takeOnSuccess=*/ false, mayDeferChecks);
}
#else
static DynamicCastResult
tryCastUnwrappingSwiftValueSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType->getKind() == MetadataKind::Class);
// unboxFromSwiftValueWithType is really just a recursive casting operation...
if (swift_unboxFromSwiftValueWithType(srcValue, destLocation, destType)) {
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
#endif
/******************************************************************************/
/****************************** Class Destination *****************************/
/******************************************************************************/
static DynamicCastResult
tryCastToSwiftClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Class);
auto destClassType = cast<ClassMetadata>(destType);
switch (srcType->getKind()) {
case MetadataKind::Class: // Swift class => Swift class
case MetadataKind::ObjCClassWrapper: { // Obj-C class => Swift class
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// Note: srcObject can be null in compatibility mode.
if (srcObject == nullptr) {
return DynamicCastResult::Failure;
}
if (auto t = swift_dynamicCastClass(srcObject, destClassType)) {
auto castObject = const_cast<void *>(t);
*(reinterpret_cast<void **>(destLocation)) = castObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
swift_unknownObjectRetain(castObject);
return DynamicCastResult::SuccessViaCopy;
}
} else {
srcFailureType = srcType;
destFailureType = destType;
return DynamicCastResult::Failure;
}
}
case MetadataKind::ForeignClass: // CF class => Swift class
// Top-level code will "unwrap" to an Obj-C class and try again.
return DynamicCastResult::Failure;
default:
return DynamicCastResult::Failure;
}
}
static DynamicCastResult
tryCastToObjectiveCClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ObjCClassWrapper);
#if SWIFT_OBJC_INTEROP
auto destObjCType = cast<ObjCClassWrapperMetadata>(destType);
switch (srcType->getKind()) {
case MetadataKind::Class: // Swift class => Obj-C class
case MetadataKind::ObjCClassWrapper: // Obj-C class => Obj-C class
case MetadataKind::ForeignClass: { // CF class => Obj-C class
auto srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If object is null, then we're in the compatibility mode.
// Earlier cast logic always succeeded `as!` casts of nil
// class references but failed `as?` and `is`
if (srcObject == nullptr) {
if (mayDeferChecks) {
*reinterpret_cast<const void **>(destLocation) = nullptr;
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
auto destObjCClass = destObjCType->Class;
if (auto resultObject
= swift_dynamicCastObjCClass(srcObject, destObjCClass)) {
*reinterpret_cast<const void **>(destLocation) = resultObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
objc_retain((id)const_cast<void *>(resultObject));
return DynamicCastResult::SuccessViaCopy;
}
}
break;
}
default:
break;
}
#endif
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToForeignClass(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
#if SWIFT_OBJC_INTEROP
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ForeignClass);
auto destClassType = cast<ForeignClassMetadata>(destType);
switch (srcType->getKind()) {
case MetadataKind::Class: // Swift class => CF class
case MetadataKind::ObjCClassWrapper: // Obj-C class => CF class
case MetadataKind::ForeignClass: { // CF class => CF class
auto srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, then we're in compatibility mode.
// Earlier cast logic always succeeded `as!` casts of nil
// class references. Yes, this is very dangerous, which
// is why we no longer permit it.
if (srcObject == nullptr) {
if (mayDeferChecks) {
*reinterpret_cast<const void **>(destLocation) = nullptr;
return DynamicCastResult::SuccessViaCopy;
} else {
// `as?` and `is` checks always fail on nil sources
return DynamicCastResult::Failure;
}
}
if (auto resultObject
= swift_dynamicCastForeignClass(srcObject, destClassType)) {
*reinterpret_cast<const void **>(destLocation) = resultObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
objc_retain((id)const_cast<void *>(resultObject));
return DynamicCastResult::SuccessViaCopy;
}
}
break;
}
default:
break;
}
#endif
return DynamicCastResult::Failure;
}
/******************************************************************************/
/***************************** Enum Destination *******************************/
/******************************************************************************/
static DynamicCastResult
tryCastToEnum(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
// Note: Optional is handled elsewhere
assert(destType->getKind() == MetadataKind::Enum);
// Enum has no special cast support at present.
return DynamicCastResult::Failure;
}
/******************************************************************************/
/**************************** Struct Destination ******************************/
/******************************************************************************/
// internal func _arrayDownCastIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Array<SourceValue>>,
// _ target: UnsafeMutablePointer<Array<TargetValue>>)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_arrayDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
// internal func _arrayDownCastConditionalIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Array<SourceValue>>,
// _ target: UnsafeMutablePointer<Array<TargetValue>>
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_arrayDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType);
// internal func _setDownCastIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Set<SourceValue>>,
// _ target: UnsafeMutablePointer<Set<TargetValue>>)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_setDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType,
const void *sourceValueHashable,
const void *targetValueHashable);
// internal func _setDownCastConditionalIndirect<SourceValue, TargetValue>(
// _ source: UnsafePointer<Set<SourceValue>>,
// _ target: UnsafeMutablePointer<Set<TargetValue>>
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_setDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceValueType,
const Metadata *targetValueType,
const void *sourceValueHashable,
const void *targetValueHashable);
// internal func _dictionaryDownCastIndirect<SourceKey, SourceValue,
// TargetKey, TargetValue>(
// _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,
// _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>)
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
void _swift_dictionaryDownCastIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType,
const void *sourceKeyHashable,
const void *targetKeyHashable);
// internal func _dictionaryDownCastConditionalIndirect<SourceKey, SourceValue,
// TargetKey, TargetValue>(
// _ source: UnsafePointer<Dictionary<SourceKey, SourceValue>>,
// _ target: UnsafeMutablePointer<Dictionary<TargetKey, TargetValue>>
// ) -> Bool
SWIFT_CC(swift) SWIFT_RUNTIME_STDLIB_INTERNAL
bool _swift_dictionaryDownCastConditionalIndirect(OpaqueValue *destination,
OpaqueValue *source,
const Metadata *sourceKeyType,
const Metadata *sourceValueType,
const Metadata *targetKeyType,
const Metadata *targetValueType,
const void *sourceKeyHashable,
const void *targetKeyHashable);
#if SWIFT_OBJC_INTEROP
// Helper to memoize bridging conformance data for a particular
// Swift struct type. This is used to speed up the most common
// ObjC->Swift bridging conversions by eliminating repeated
// protocol conformance lookups.
// Currently used only for String, which may be the only
// type used often enough to justify the extra static memory.
struct ObjCBridgeMemo {
#if !NDEBUG
// Used in assert build to verify that we always get called with
// the same destType
const Metadata *destType;
#endif
const _ObjectiveCBridgeableWitnessTable *destBridgeWitness;
const Metadata *targetBridgedType;
Class targetBridgedObjCClass;
swift_once_t fetchWitnessOnce;
DynamicCastResult tryBridge(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
struct SetupData {
const Metadata *destType;
struct ObjCBridgeMemo *memo;
} setupData { destType, this };
swift_once(&fetchWitnessOnce,
[](void *data) {
struct SetupData *setupData = (struct SetupData *)data;
struct ObjCBridgeMemo *memo = setupData->memo;
#if !NDEBUG
memo->destType = setupData->destType;
#endif
memo->destBridgeWitness = findBridgeWitness(setupData->destType);
if (memo->destBridgeWitness == nullptr) {
memo->targetBridgedType = nullptr;
memo->targetBridgedObjCClass = nullptr;
} else {
memo->targetBridgedType = _getBridgedObjectiveCType(
MetadataState::Complete, setupData->destType, memo->destBridgeWitness).Value;
assert(memo->targetBridgedType->getKind() == MetadataKind::ObjCClassWrapper);
memo->targetBridgedObjCClass = memo->targetBridgedType->getObjCClassObject();
assert(memo->targetBridgedObjCClass != nullptr);
}
}, (void *)&setupData);
// Check that this always gets called with the same destType.
assert((destType == this->destType) && "ObjC casting memo used inconsistently");
// !! If bridging is not usable, stop here.
if (targetBridgedObjCClass == nullptr) {
return DynamicCastResult::Failure;
}
// Use the dynamic ISA type of the object always (Note that this
// also implicitly gives us the ObjC type for a CF object.)
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, then we're in backwards compatibility mode.
if (srcObject == nullptr) {
return DynamicCastResult::Failure;
}
Class srcObjCType = object_getClass((id)srcObject);
// Fail if the ObjC object is not a subclass of the bridge class.
while (srcObjCType != targetBridgedObjCClass) {
srcObjCType = class_getSuperclass(srcObjCType);
if (srcObjCType == nullptr) {
return DynamicCastResult::Failure;
}
}
// The ObjC object is an acceptable type, so call the bridge function...
return _tryCastFromClassToObjCBridgeable(
destLocation, destType, srcValue, srcType, srcObject,
destFailureType, srcFailureType,
takeOnSuccess, mayDeferChecks,
destBridgeWitness, targetBridgedType);
}
};
#endif
static DynamicCastResult
tryCastToAnyHashable(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &STRUCT_TYPE_DESCR_SYM(s11AnyHashable));
const HashableWitnessTable *hashableConformance = nullptr;
switch (srcType->getKind()) {
case MetadataKind::ForeignClass: // CF -> String
case MetadataKind::ObjCClassWrapper: { // Obj-C -> String
#if SWIFT_OBJC_INTEROP
auto cls = srcType;
auto nsString = getNSStringMetadata();
do {
if (cls == nsString) {
hashableConformance = getNSStringHashableConformance();
break;
}
cls = _swift_class_getSuperclass(cls);
} while (cls != nullptr);
break;
#else
// If no Obj-C interop, just fall through to the general case.
break;
#endif
}
case MetadataKind::Optional: {
// FIXME: https://github.com/apple/swift/issues/51550
// Until the interactions between AnyHashable and Optional is fixed, we
// avoid directly injecting Optionals. In particular, this allows casts
// from [String?:String] to [AnyHashable:Any] to work the way people
// expect. Otherwise, the resulting dictionary can only be indexed with an
// explicit Optional<String>, not a plain String.
// After fixing the issue, we can consider dropping this special
// case entirely.
// !!!! This breaks compatibility with compiler-optimized casts
// (which just inject) and violates the Casting Spec. It just preserves
// the behavior of the older casting code until we can clean things up.
auto srcInnerType = cast<EnumMetadata>(srcType)->getGenericArgs()[0];
unsigned sourceEnumCase = srcInnerType->vw_getEnumTagSinglePayload(
srcValue, /*emptyCases=*/1);
auto nonNil = (sourceEnumCase == 0);
if (nonNil) {
return DynamicCastResult::Failure; // Our caller will unwrap the optional and try again
}
// Else Optional is nil -- the general case below will inject it
break;
}
default:
break;
}
// General case: If it conforms to Hashable, we cast it
if (hashableConformance == nullptr) {
hashableConformance = reinterpret_cast<const HashableWitnessTable *>(
swift_conformsToProtocolCommon(srcType, &HashableProtocolDescriptor)
);
}
if (hashableConformance) {
_swift_convertToAnyHashableIndirect(srcValue, destLocation,
srcType, hashableConformance);
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
static DynamicCastResult
tryCastToArray(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(Sa));
switch (srcType->getKind()) {
case MetadataKind::Struct: { // Struct -> Array
const auto srcStructType = cast<StructMetadata>(srcType);
if (srcStructType->Description == &NOMINAL_TYPE_DESCR_SYM(Sa)) { // Array -> Array
auto sourceArgs = srcType->getGenericArgs();
auto destArgs = destType->getGenericArgs();
if (mayDeferChecks) {
_swift_arrayDownCastIndirect(
srcValue, destLocation, sourceArgs[0], destArgs[0]);
return DynamicCastResult::SuccessViaCopy;
} else {
auto result = _swift_arrayDownCastConditionalIndirect(
srcValue, destLocation, sourceArgs[0], destArgs[0]);
if (result) {
return DynamicCastResult::SuccessViaCopy;
}
}
}
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToDictionary(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(SD));
switch (srcType->getKind()) {
case MetadataKind::Struct: { // Struct -> Dictionary
const auto srcStructType = cast<StructMetadata>(srcType);
if (srcStructType->Description == &NOMINAL_TYPE_DESCR_SYM(SD)) { // Dictionary -> Dictionary
auto sourceArgs = srcType->getGenericArgs();
auto destArgs = destType->getGenericArgs();
if (mayDeferChecks) {
_swift_dictionaryDownCastIndirect(
srcValue, destLocation, sourceArgs[0], sourceArgs[1],
destArgs[0], destArgs[1], sourceArgs[2], destArgs[2]);
return DynamicCastResult::SuccessViaCopy;
} else {
auto result = _swift_dictionaryDownCastConditionalIndirect(
srcValue, destLocation, sourceArgs[0], sourceArgs[1],
destArgs[0], destArgs[1], sourceArgs[2], destArgs[2]);
if (result) {
return DynamicCastResult::SuccessViaCopy;
}
}
}
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToSet(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(Sh));
switch (srcType->getKind()) {
case MetadataKind::Struct: { // Struct -> Set
const auto srcStructType = cast<StructMetadata>(srcType);
if (srcStructType->Description == &NOMINAL_TYPE_DESCR_SYM(Sh)) { // Set -> Set
auto sourceArgs = srcType->getGenericArgs();
auto destArgs = destType->getGenericArgs();
if (mayDeferChecks) {
_swift_setDownCastIndirect(srcValue, destLocation,
sourceArgs[0], destArgs[0], sourceArgs[1], destArgs[1]);
return DynamicCastResult::SuccessViaCopy;
} else {
auto result = _swift_setDownCastConditionalIndirect(
srcValue, destLocation,
sourceArgs[0], destArgs[0],
sourceArgs[1], destArgs[1]);
if (result) {
return DynamicCastResult::SuccessViaCopy;
}
}
}
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToString(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
assert(cast<StructMetadata>(destType)->Description
== &NOMINAL_TYPE_DESCR_SYM(SS));
switch (srcType->getKind()) {
case MetadataKind::ForeignClass: // CF -> String
case MetadataKind::ObjCClassWrapper: { // Obj-C -> String
#if SWIFT_OBJC_INTEROP
static ObjCBridgeMemo memo;
return memo.tryBridge(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType,
takeOnSuccess, mayDeferChecks);
#else
SWIFT_FALLTHROUGH;
#endif
}
default:
return DynamicCastResult::Failure;
}
return DynamicCastResult::Failure;
}
static DynamicCastResult
tryCastToStruct(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Struct);
// There is no special cast handling at present for general Struct types.
// Special logic for AnyHashable, Set, Dictionary, Array, and String
// is broken out above. See also selectCasterForDest() for the
// logic that chooses one of these functions.
return DynamicCastResult::Failure;
}
/******************************************************************************/
/*************************** Optional Destination *****************************/
/******************************************************************************/
static DynamicCastResult
tryCastToOptional(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Optional);
// Nothing to do for the basic casting operation.
// Unwrapping is handled by top-level tryCast with assistance
// from utility functions below.
return DynamicCastResult::Failure;
}
// The nil value `T?.none` can be cast to any optional type.
// When the unwrapper sees a source value that is nil, it calls
// tryCastFromNil() to try to set the target optional to nil.
//
// This is complicated by the desire to preserve the nesting
// as far as possible. For example, we would like:
// Int?.none => Int??.some(.none)
// Int??.none => Any????.some(.some(.none))
// Of course, if the target is shallower than the source,
// then we have to just set the outermost optional to nil.
// This helper sets a nested optional to nil at a requested level:
static void
initializeToNilAtDepth(OpaqueValue *destLocation, const Metadata *destType, int depth) {
assert(destType->getKind() == MetadataKind::Optional);
auto destInnerType = cast<EnumMetadata>(destType)->getGenericArgs()[0];
if (depth > 0) {
initializeToNilAtDepth(destLocation, destInnerType, depth - 1);
// Set .some at each level as we unwind
destInnerType->vw_storeEnumTagSinglePayload(
destLocation, 0, 1);
} else {
// Set .none at the lowest level
destInnerType->vw_storeEnumTagSinglePayload(
destLocation, 1, 1);
}
}
static void
copyNilPreservingDepth(OpaqueValue *destLocation, const Metadata *destType, const Metadata *srcType)
{
assert(srcType->getKind() == MetadataKind::Optional);
assert(destType->getKind() == MetadataKind::Optional);
// Measure how deep the source nil is: Is it Int?.none or Int??.none or ...
auto srcInnerType = cast<EnumMetadata>(srcType)->getGenericArgs()[0];
int srcDepth = 1;
while (srcInnerType->getKind() == MetadataKind::Optional) {
srcInnerType = cast<EnumMetadata>(srcInnerType)->getGenericArgs()[0];
srcDepth += 1;
}
// Measure how deep the destination optional is
auto destInnerType = cast<EnumMetadata>(destType)->getGenericArgs()[0];
int destDepth = 1;
while (destInnerType->getKind() == MetadataKind::Optional) {
destInnerType = cast<EnumMetadata>(destInnerType)->getGenericArgs()[0];
destDepth += 1;
}
// Recursively set the destination to .some(.some(... .some(.none)))
auto targetDepth = std::max(destDepth - srcDepth, 0);
initializeToNilAtDepth(destLocation, destType, targetDepth);
}
// Try unwrapping both source and dest optionals together.
// If the source is nil, then cast that to the destination.
static DynamicCastResult
tryCastUnwrappingOptionalBoth(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(destType->getKind() == MetadataKind::Optional);
assert(srcType->getKind() == MetadataKind::Optional);
auto srcInnerType = cast<EnumMetadata>(srcType)->getGenericArgs()[0];
unsigned sourceEnumCase = srcInnerType->vw_getEnumTagSinglePayload(
srcValue, /*emptyCases=*/1);
auto sourceIsNil = (sourceEnumCase != 0);
if (sourceIsNil) {
if (runtime::bincompat::useLegacyOptionalNilInjectionInCasting()) {
auto destInnerType = cast<EnumMetadata>(destType)->getGenericArgs()[0];
// Set .none at the outer level
destInnerType->vw_storeEnumTagSinglePayload(destLocation, 1, 1);
} else {
copyNilPreservingDepth(destLocation, destType, srcType);
}
return DynamicCastResult::SuccessViaCopy; // nil was essentially copied to dest
} else {
auto destEnumType = cast<EnumMetadata>(destType);
const Metadata *destInnerType = destEnumType->getGenericArgs()[0];
auto destInnerLocation = destLocation; // Single-payload enum layout
auto subcastResult = tryCast(
destInnerLocation, destInnerType, srcValue, srcInnerType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
destInnerType->vw_storeEnumTagSinglePayload(
destLocation, /*case*/ 0, /*emptyCases*/ 1);
}
return subcastResult;
}
return DynamicCastResult::Failure;
}
// Try unwrapping just the destination optional.
// Note we do this even if both src and dest are optional.
// For example, Int -> Any? requires unwrapping the destination
// in order to inject the Int into the existential.
static DynamicCastResult
tryCastUnwrappingOptionalDestination(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(destType->getKind() == MetadataKind::Optional);
auto destEnumType = cast<EnumMetadata>(destType);
const Metadata *destInnerType = destEnumType->getGenericArgs()[0];
auto destInnerLocation = destLocation; // Single-payload enum layout
auto subcastResult = tryCast(
destInnerLocation, destInnerType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
destInnerType->vw_storeEnumTagSinglePayload(
destLocation, /*case*/ 0, /*emptyCases*/ 1);
}
return subcastResult;
}
// Try unwrapping just the source optional.
// Note we do this even if both target and dest are optional.
// For example, this is used when extracting the contents of
// an Optional<Any>.
static DynamicCastResult
tryCastUnwrappingOptionalSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType->getKind() == MetadataKind::Optional);
auto srcInnerType = cast<EnumMetadata>(srcType)->getGenericArgs()[0];
unsigned sourceEnumCase = srcInnerType->vw_getEnumTagSinglePayload(
srcValue, /*emptyCases=*/1);
auto nonNil = (sourceEnumCase == 0);
if (nonNil) {
// Recurse with unwrapped source
return tryCast(destLocation, destType, srcValue, srcInnerType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
}
return DynamicCastResult::Failure;
}
/******************************************************************************/
/***************************** Tuple Destination ******************************/
/******************************************************************************/
// The only thing that can be legally cast to a tuple is another tuple.
// Most of the logic below is required to handle element-wise casts of
// tuples that are compatible but not of the same type.
static DynamicCastResult
tryCastToTuple(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Tuple);
const auto destTupleType = cast<TupleTypeMetadata>(destType);
srcFailureType = srcType;
destFailureType = destType;
// We cannot cast non-tuple data to a tuple
if (srcType->getKind() != MetadataKind::Tuple) {
return DynamicCastResult::Failure;
}
const auto srcTupleType = cast<TupleTypeMetadata>(srcType);
// Tuples must have same number of elements
if (srcTupleType->NumElements != destTupleType->NumElements) {
return DynamicCastResult::Failure;
}
// Common labels must match
const char *srcLabels = srcTupleType->Labels;
const char *destLabels = destTupleType->Labels;
while (srcLabels != nullptr
&& destLabels != nullptr
&& srcLabels != destLabels)
{
const char *srcSpace = strchr(srcLabels, ' ');
const char *destSpace = strchr(destLabels, ' ');
// If we've reached the end of either label string, we're done.
if (srcSpace == nullptr || destSpace == nullptr) {
break;
}
// If both labels are non-empty, and the labels mismatch, we fail.
if (srcSpace != srcLabels && destSpace != destLabels) {
unsigned srcLen = srcSpace - srcLabels;
unsigned destLen = destSpace - destLabels;
if (srcLen != destLen ||
strncmp(srcLabels, destLabels, srcLen) != 0)
return DynamicCastResult::Failure;
}
srcLabels = srcSpace + 1;
destLabels = destSpace + 1;
}
// Compare the element types to see if they all match.
bool typesMatch = true;
auto numElements = srcTupleType->NumElements;
for (unsigned i = 0; typesMatch && i != numElements; ++i) {
if (srcTupleType->getElement(i).Type != destTupleType->getElement(i).Type) {
typesMatch = false;
break;
}
}
if (typesMatch) {
// The actual element types are identical, so we can use the
// fast value-witness machinery for the whole tuple.
if (takeOnSuccess) {
srcType->vw_initializeWithTake(destLocation, srcValue);
return DynamicCastResult::SuccessViaTake;
} else {
srcType->vw_initializeWithCopy(destLocation, srcValue);
return DynamicCastResult::SuccessViaCopy;
}
} else {
// Slow path casts each item separately.
for (unsigned j = 0, n = srcTupleType->NumElements; j != n; ++j) {
const auto &srcElt = srcTupleType->getElement(j);
const auto &destElt = destTupleType->getElement(j);
auto subcastResult = tryCast(destElt.findIn(destLocation), destElt.Type,
srcElt.findIn(srcValue), srcElt.Type,
destFailureType, srcFailureType,
false, mayDeferChecks);
if (subcastResult == DynamicCastResult::Failure) {
for (unsigned k = 0; k != j; ++k) {
const auto &elt = destTupleType->getElement(k);
elt.Type->vw_destroy(elt.findIn(destLocation));
}
return DynamicCastResult::Failure;
}
}
// We succeeded by casting each item.
return DynamicCastResult::SuccessViaCopy;
}
}
/******************************************************************************/
/**************************** Function Destination ****************************/
/******************************************************************************/
// The only thing that can be legally cast to a function is another function.
static DynamicCastResult
tryCastToFunction(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Function);
const auto destFuncType = cast<FunctionTypeMetadata>(destType);
// Function casts succeed on exact matches, or if the target type is
// throwier than the source type.
//
// TODO: We could also allow ABI-compatible variance, such as casting
// a dynamic Base -> Derived to Derived -> Base. We wouldn't be able to
// perform a dynamic cast that required any ABI adjustment without a JIT
// though.
if (srcType->getKind() != MetadataKind::Function) {
return DynamicCastResult::Failure;
}
auto srcFuncType = cast<FunctionTypeMetadata>(srcType);
// Check that argument counts and convention match (but ignore
// "throws" for now).
if (srcFuncType->Flags.withThrows(false)
!= destFuncType->Flags.withThrows(false)) {
return DynamicCastResult::Failure;
}
// If the target type can't throw, neither can the source.
if (srcFuncType->isThrowing() && !destFuncType->isThrowing())
return DynamicCastResult::Failure;
// The result and argument types must match.
if (srcFuncType->ResultType != destFuncType->ResultType)
return DynamicCastResult::Failure;
if (srcFuncType->getNumParameters() != destFuncType->getNumParameters())
return DynamicCastResult::Failure;
if (srcFuncType->hasParameterFlags() != destFuncType->hasParameterFlags())
return DynamicCastResult::Failure;
for (unsigned i = 0, e = srcFuncType->getNumParameters(); i < e; ++i) {
if (srcFuncType->getParameter(i) != destFuncType->getParameter(i) ||
srcFuncType->getParameterFlags(i) != destFuncType->getParameterFlags(i))
return DynamicCastResult::Failure;
}
// Everything matches, so we can take/copy the function reference.
if (takeOnSuccess) {
srcType->vw_initializeWithTake(destLocation, srcValue);
return DynamicCastResult::SuccessViaTake;
} else {
srcType->vw_initializeWithCopy(destLocation, srcValue);
return DynamicCastResult::SuccessViaCopy;
}
}
/******************************************************************************/
/************************** Existential Destination ***************************/
/******************************************************************************/
/// Check whether a type conforms to the given protocols, filling in a
/// list of conformances.
static bool _conformsToProtocols(const OpaqueValue *value,
const Metadata *type,
const ExistentialTypeMetadata *existentialType,
const WitnessTable **conformances) {
if (auto *superclass = existentialType->getSuperclassConstraint()) {
if (!swift_dynamicCastMetatype(type, superclass))
return false;
}
if (existentialType->isClassBounded()) {
if (!Metadata::isAnyKindOfClass(type->getKind()))
return false;
}
for (auto protocol : existentialType->getProtocols()) {
if (!swift::_conformsToProtocol(value, type, protocol, conformances))
return false;
if (conformances != nullptr && protocol.needsWitnessTable()) {
assert(*conformances != nullptr);
++conformances;
}
}
return true;
}
// Cast to unconstrained `Any`
static DynamicCastResult
tryCastToUnconstrainedOpaqueExistential(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Existential);
assert(cast<ExistentialTypeMetadata>(destType)->getRepresentation()
== ExistentialTypeRepresentation::Opaque);
auto destExistential
= reinterpret_cast<OpaqueExistentialContainer *>(destLocation);
// Fill in the type and value.
destExistential->Type = srcType;
auto *destBox = srcType->allocateBoxForExistentialIn(&destExistential->Buffer);
if (takeOnSuccess) {
srcType->vw_initializeWithTake(destBox, srcValue);
return DynamicCastResult::SuccessViaTake;
} else {
srcType->vw_initializeWithCopy(destBox, srcValue);
return DynamicCastResult::SuccessViaCopy;
}
}
// Cast to constrained `Any`
static DynamicCastResult
tryCastToConstrainedOpaqueExistential(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Existential);
auto destExistentialType = cast<ExistentialTypeMetadata>(destType);
assert(destExistentialType->getRepresentation()
== ExistentialTypeRepresentation::Opaque);
auto destExistential
= reinterpret_cast<OpaqueExistentialContainer *>(destLocation);
// Check for protocol conformances and fill in the witness tables.
// TODO (rdar://17033499) If the source is an existential, we should
// be able to compare the protocol constraints more efficiently than this.
if (_conformsToProtocols(srcValue, srcType, destExistentialType,
destExistential->getWitnessTables())) {
return tryCastToUnconstrainedOpaqueExistential(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
} else {
return DynamicCastResult::Failure;
}
}
static DynamicCastResult
tryCastToClassExistential(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Existential);
auto destExistentialType = cast<ExistentialTypeMetadata>(destType);
assert(destExistentialType->getRepresentation()
== ExistentialTypeRepresentation::Class);
auto destExistentialLocation
= reinterpret_cast<ClassExistentialContainer *>(destLocation);
MetadataKind srcKind = srcType->getKind();
switch (srcKind) {
case MetadataKind::Metatype: {
#if SWIFT_OBJC_INTEROP
// Get an object reference to the metatype and try fitting that into
// the existential...
auto metatypePtr = reinterpret_cast<const Metadata **>(srcValue);
auto metatype = *metatypePtr;
if (auto tmp = swift_dynamicCastMetatypeToObjectConditional(metatype)) {
auto value = reinterpret_cast<OpaqueValue *>(&tmp);
auto type = reinterpret_cast<const Metadata *>(tmp);
if (_conformsToProtocols(value, type, destExistentialType,
destExistentialLocation->getWitnessTables())) {
auto object = *(reinterpret_cast<HeapObject **>(value));
destExistentialLocation->Value = object;
if (takeOnSuccess) {
// We copied the pointer without retain, so the source is no
// longer valid...
return DynamicCastResult::SuccessViaTake;
} else {
swift_unknownObjectRetain(object);
return DynamicCastResult::SuccessViaCopy;
}
} else {
// We didn't assign to destination, so the source reference
// is still valid and the reference count is still correct.
}
}
#endif
return DynamicCastResult::Failure;
}
case MetadataKind::ObjCClassWrapper:
#if SWIFT_OBJC_INTEROP
id srcObject;
memcpy(&srcObject, srcValue, sizeof(id));
if (!runtime::bincompat::useLegacySwiftValueUnboxingInCasting()) {
if (getAsSwiftValue(srcObject) != nullptr) {
// Do not directly cast a `__SwiftValue` box
// Return failure so our caller will unwrap and try again
return DynamicCastResult::Failure;
}
}
#endif
SWIFT_FALLTHROUGH;
case MetadataKind::Class:
case MetadataKind::ForeignClass: {
auto srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, then we're in compatibility mode.
// Earlier cast logic always succeeded `as!` casts of nil
// class references:
if (srcObject == nullptr) {
if (mayDeferChecks) {
*reinterpret_cast<const void **>(destLocation) = nullptr;
return DynamicCastResult::SuccessViaCopy;
} else {
return DynamicCastResult::Failure;
}
}
if (_conformsToProtocols(srcValue, srcType,
destExistentialType,
destExistentialLocation->getWitnessTables())) {
destExistentialLocation->Value = srcObject;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
swift_unknownObjectRetain(srcObject);
return DynamicCastResult::SuccessViaCopy;
}
}
return DynamicCastResult::Failure;
}
default:
return DynamicCastResult::Failure;
}
return DynamicCastResult::Failure;
}
// SwiftValue boxing is a failsafe that we only want to invoke
// after other approaches have failed. This is why it's not
// integrated into tryCastToClassExistential() above.
static DynamicCastResult
tryCastToClassExistentialViaSwiftValue(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Existential);
auto destExistentialType = cast<ExistentialTypeMetadata>(destType);
assert(destExistentialType->getRepresentation()
== ExistentialTypeRepresentation::Class);
auto destExistentialLocation
= reinterpret_cast<ClassExistentialContainer *>(destLocation);
switch (srcType->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
// Class references always go directly into
// class existentials; it makes no sense to wrap them.
return DynamicCastResult::Failure;
case MetadataKind::Metatype: {
#if SWIFT_OBJC_INTEROP
auto metatypePtr = reinterpret_cast<const Metadata **>(srcValue);
auto metatype = *metatypePtr;
switch (metatype->getKind()) {
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass:
// Exclude class metatypes on Darwin, since those are object types and can
// be stored directly.
return DynamicCastResult::Failure;
default:
break;
}
#endif
// Non-class metatypes are never objects, and
// metatypes on non-Darwin are never objects, so
// fall through to box those.
SWIFT_FALLTHROUGH;
}
default: {
// We can always box when the destination is a simple
// (unconstrained) `AnyObject`.
if (destExistentialType->NumProtocols != 0) {
// But if there are constraints...
if (!runtime::bincompat::useLegacyObjCBoxingInCasting()) {
// ... never box if we're not supporting legacy semantics.
return DynamicCastResult::Failure;
}
// Legacy behavior: We used to permit casts to a constrained (existential)
// type if the resulting `__SwiftValue` box conformed to the target type.
// This is no longer supported, since it caused `x is NSCopying` to be
// true even when x does not in fact implement the requirements of
// `NSCopying`.
#if SWIFT_OBJC_INTEROP
if (!findSwiftValueConformances(
destExistentialType, destExistentialLocation->getWitnessTables())) {
return DynamicCastResult::Failure;
}
#else
if (!swift_swiftValueConformsTo(destType, destType)) {
return DynamicCastResult::Failure;
}
#endif
}
#if SWIFT_OBJC_INTEROP
auto object = bridgeAnythingToSwiftValueObject(
srcValue, srcType, takeOnSuccess);
destExistentialLocation->Value = object;
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
return DynamicCastResult::SuccessViaCopy;
}
# else
// Note: Code below works correctly on both Obj-C and non-Obj-C platforms,
// but the code above is slightly faster on Obj-C platforms.
auto object = _bridgeAnythingToObjectiveC(srcValue, srcType);
destExistentialLocation->Value = object;
return DynamicCastResult::SuccessViaCopy;
#endif
}
}
}
static DynamicCastResult
tryCastToErrorExistential(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Existential);
auto destExistentialType = cast<ExistentialTypeMetadata>(destType);
assert(destExistentialType->getRepresentation()
== ExistentialTypeRepresentation::Error);
auto destBoxAddr = reinterpret_cast<SwiftError **>(destLocation);
MetadataKind srcKind = srcType->getKind();
switch (srcKind) {
case MetadataKind::ForeignClass: // CF object => Error
case MetadataKind::ObjCClassWrapper: // Obj-C object => Error
case MetadataKind::Struct: // Struct => Error
case MetadataKind::Enum: // Enum => Error
case MetadataKind::Class: { // Class => Error
assert(destExistentialType->NumProtocols == 1);
const WitnessTable *errorWitness;
if (_conformsToProtocols(
srcValue, srcType, destExistentialType, &errorWitness)) {
#if SWIFT_OBJC_INTEROP
// If it already holds an NSError, just use that.
if (auto embedded = getErrorEmbeddedNSErrorIndirect(
srcValue, srcType, errorWitness)) {
*destBoxAddr = reinterpret_cast<SwiftError *>(embedded);
return DynamicCastResult::SuccessViaCopy;
}
#endif
BoxPair destBox = swift_allocError(
srcType, errorWitness, srcValue, takeOnSuccess);
*destBoxAddr = reinterpret_cast<SwiftError *>(destBox.object);
if (takeOnSuccess) {
return DynamicCastResult::SuccessViaTake;
} else {
return DynamicCastResult::SuccessViaCopy;
}
}
return DynamicCastResult::Failure;
}
default:
return DynamicCastResult::Failure;
}
}
static DynamicCastResult
tryCastUnwrappingExistentialSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(srcType->getKind() == MetadataKind::Existential);
auto srcExistentialType = cast<ExistentialTypeMetadata>(srcType);
// Unpack the existential content
const Metadata *srcInnerType;
OpaqueValue *srcInnerValue;
switch (srcExistentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Class: {
auto classContainer
= reinterpret_cast<ClassExistentialContainer *>(srcValue);
srcInnerType = swift_getObjectType((HeapObject *)classContainer->Value);
srcInnerValue = reinterpret_cast<OpaqueValue *>(&classContainer->Value);
break;
}
case ExistentialTypeRepresentation::Opaque: {
auto opaqueContainer
= reinterpret_cast<OpaqueExistentialContainer*>(srcValue);
srcInnerType = opaqueContainer->Type;
srcInnerValue = srcExistentialType->projectValue(srcValue);
break;
}
case ExistentialTypeRepresentation::Error: {
const SwiftError *errorBox
= *reinterpret_cast<const SwiftError * const *>(srcValue);
auto srcErrorValue
= errorBox->isPureNSError() ? srcValue : errorBox->getValue();
srcInnerType = errorBox->getType();
srcInnerValue = const_cast<OpaqueValue *>(srcErrorValue);
break;
}
}
srcFailureType = srcInnerType;
return tryCast(destLocation, destType,
srcInnerValue, srcInnerType,
destFailureType, srcFailureType,
takeOnSuccess && (srcInnerValue == srcValue),
mayDeferChecks);
}
static DynamicCastResult tryCastUnwrappingExtendedExistentialSource(
OpaqueValue *destLocation, const Metadata *destType, OpaqueValue *srcValue,
const Metadata *srcType, const Metadata *&destFailureType,
const Metadata *&srcFailureType, bool takeOnSuccess, bool mayDeferChecks) {
assert(srcType != destType);
assert(srcType->getKind() == MetadataKind::ExtendedExistential);
auto srcExistentialType = cast<ExtendedExistentialTypeMetadata>(srcType);
// Unpack the existential content
const Metadata *srcInnerType = nullptr;
OpaqueValue *srcInnerValue = nullptr;
switch (srcExistentialType->Shape->Flags.getSpecialKind()) {
case ExtendedExistentialTypeShape::SpecialKind::None: {
auto opaqueContainer =
reinterpret_cast<OpaqueExistentialContainer *>(srcValue);
srcInnerType = opaqueContainer->Type;
srcInnerValue = const_cast<OpaqueValue *>(opaqueContainer->projectValue());
break;
}
case ExtendedExistentialTypeShape::SpecialKind::Class: {
auto classContainer =
reinterpret_cast<ClassExistentialContainer *>(srcValue);
srcInnerType = swift_getObjectType((HeapObject *)classContainer->Value);
srcInnerValue = reinterpret_cast<OpaqueValue *>(&classContainer->Value);
break;
}
case ExtendedExistentialTypeShape::SpecialKind::Metatype: {
auto srcExistentialContainer =
reinterpret_cast<ExistentialMetatypeContainer *>(srcValue);
srcInnerType = swift_getMetatypeMetadata(srcExistentialContainer->Value);
srcInnerValue = reinterpret_cast<OpaqueValue *>(&srcExistentialContainer->Value);
break;
}
case ExtendedExistentialTypeShape::SpecialKind::ExplicitLayout: {
swift_unreachable("Explicit layout not yet implemented");
break;
}
}
srcFailureType = srcInnerType;
return tryCast(destLocation, destType, srcInnerValue, srcInnerType,
destFailureType, srcFailureType,
takeOnSuccess && (srcInnerValue == srcValue), mayDeferChecks);
}
static DynamicCastResult
tryCastUnwrappingExistentialMetatypeSource(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(srcType->getKind() == MetadataKind::ExistentialMetatype);
auto srcExistentialContainer = reinterpret_cast<ExistentialMetatypeContainer *>(srcValue);
auto srcInnerValue = reinterpret_cast<OpaqueValue *>(&srcExistentialContainer->Value);
assert((const void *)srcInnerValue == (const void *)srcValue);
auto srcInnerValueAsType = srcExistentialContainer->Value;
const Metadata *srcInnerType = swift_getMetatypeMetadata(srcInnerValueAsType);
srcFailureType = srcInnerType;
return tryCast(destLocation, destType,
srcInnerValue, srcInnerType,
destFailureType, srcFailureType,
takeOnSuccess && (srcInnerValue == srcValue),
mayDeferChecks);
}
static DynamicCastResult tryCastToExtendedExistential(
OpaqueValue *destLocation, const Metadata *destType, OpaqueValue *srcValue,
const Metadata *srcType, const Metadata *&destFailureType,
const Metadata *&srcFailureType, bool takeOnSuccess, bool mayDeferChecks) {
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ExtendedExistential);
auto destExistentialType = cast<ExtendedExistentialTypeMetadata>(destType);
auto *destExistentialShape = destExistentialType->Shape;
const unsigned shapeArgumentCount =
destExistentialShape->getGenSigArgumentLayoutSizeInWords();
const Metadata *selfType = srcType;
// If we have a type expression to look into, unwrap as much metatype
// structure as possible so we can reach the type metadata for the 'Self'
// parameter.
if (destExistentialShape->Flags.hasTypeExpression()) {
Demangler dem;
auto *node = dem.demangleType(destExistentialShape->getTypeExpression()->name.get());
if (!node)
return DynamicCastResult::Failure;
while (node->getKind() == Demangle::Node::Kind::Type &&
node->getNumChildren() &&
node->getChild(0)->getKind() == Demangle::Node::Kind::Metatype &&
node->getChild(0)->getNumChildren()) {
auto *metatypeMetadata = dyn_cast<MetatypeMetadata>(selfType);
if (!metatypeMetadata)
return DynamicCastResult::Failure;
selfType = metatypeMetadata->InstanceType;
node = node->getChild(0)->getChild(0);
}
// Make sure the thing we've pulled out at the end is a dependent
// generic parameter.
if (!(node->getKind() == Demangle::Node::Kind::Type &&
node->getNumChildren() &&
node->getChild(0)->getKind() ==
Demangle::Node::Kind::DependentGenericParamType))
return DynamicCastResult::Failure;
}
llvm::SmallVector<const void *, 4> allGenericArgsVec;
llvm::SmallVector<const void *, 4> witnessTables;
{
// Line up the arguments to the requirement signature.
auto genArgs = destExistentialType->getGeneralizationArguments();
allGenericArgsVec.append(genArgs, genArgs + shapeArgumentCount);
// Tack on the `Self` argument.
allGenericArgsVec.push_back((const void *)selfType);
SubstGenericParametersFromMetadata substitutions(destExistentialShape,
allGenericArgsVec.data());
// Verify the requirements in the requirement signature against the
// arguments from the source value.
auto requirementSig = destExistentialShape->getRequirementSignature();
auto error = swift::_checkGenericRequirements(
requirementSig.getParams(),
requirementSig.getRequirements(),
witnessTables,
[&substitutions](unsigned depth, unsigned index) {
return substitutions.getMetadata(depth, index).Ptr;
},
[&substitutions](unsigned fullOrdinal, unsigned keyOrdinal) {
return substitutions.getMetadataKeyArgOrdinal(keyOrdinal).Ptr;
},
[](const Metadata *type, unsigned index) -> const WitnessTable * {
swift_unreachable("Resolution of witness tables is not supported");
});
if (error)
return DynamicCastResult::Failure;
}
OpaqueValue *destBox = nullptr;
const WitnessTable **destWitnesses = nullptr;
switch (destExistentialShape->Flags.getSpecialKind()) {
case ExtendedExistentialTypeShape::SpecialKind::None: {
auto destExistential =
reinterpret_cast<OpaqueExistentialContainer *>(destLocation);
// Allocate a box and fill in the type information.
destExistential->Type = srcType;
destBox = srcType->allocateBoxForExistentialIn(&destExistential->Buffer);
destWitnesses = destExistential->getWitnessTables();
break;
}
case ExtendedExistentialTypeShape::SpecialKind::Class: {
auto destExistential =
reinterpret_cast<ClassExistentialContainer *>(destLocation);
destBox = reinterpret_cast<OpaqueValue *>(&destExistential->Value);
destWitnesses = destExistential->getWitnessTables();
break;
}
case ExtendedExistentialTypeShape::SpecialKind::Metatype: {
auto destExistential =
reinterpret_cast<ExistentialMetatypeContainer *>(destLocation);
destBox = reinterpret_cast<OpaqueValue *>(&destExistential->Value);
destWitnesses = destExistential->getWitnessTables();
break;
}
case ExtendedExistentialTypeShape::SpecialKind::ExplicitLayout:
swift_unreachable("Witnesses for explicit layout not yet implemented");
}
// Fill in the trailing set of witness tables.
const unsigned numWitnessTables = witnessTables.size();
assert(numWitnessTables ==
llvm::count_if(destExistentialShape->getRequirementSignature().getRequirements(),
[](const auto &req) -> bool {
return req.getKind() ==
GenericRequirementKind::Protocol;
}));
for (unsigned i = 0; i < numWitnessTables; ++i) {
destWitnesses[i] = reinterpret_cast<const WitnessTable *>(witnessTables[i]);
}
if (takeOnSuccess) {
srcType->vw_initializeWithTake(destBox, srcValue);
return DynamicCastResult::SuccessViaTake;
} else {
srcType->vw_initializeWithCopy(destBox, srcValue);
return DynamicCastResult::SuccessViaCopy;
}
}
/******************************************************************************/
/**************************** Opaque Destination ******************************/
/******************************************************************************/
static DynamicCastResult
tryCastToOpaque(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Opaque);
// There's nothing special we can do here, but we have to have this
// empty function in order for the general casting logic to run
// for these types.
return DynamicCastResult::Failure;
}
/******************************************************************************/
/**************************** Metatype Destination ****************************/
/******************************************************************************/
#if SWIFT_OBJC_INTEROP
/// Check whether an unknown class instance is actually a type/metatype object.
static const Metadata *_getUnknownClassAsMetatype(void *object) {
// Objective-C class metadata are objects, so an AnyObject (or
// NSObject) may refer to a class object.
// Test whether the object's isa is a metaclass, which indicates that
// the object is a class.
Class isa = object_getClass((id)object);
if (class_isMetaClass(isa)) {
return swift_getObjCClassMetadata((const ClassMetadata *)object);
}
return nullptr;
}
#endif
static DynamicCastResult
tryCastToMetatype(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::Metatype);
const MetatypeMetadata *destMetatypeType = cast<MetatypeMetadata>(destType);
MetadataKind srcKind = srcType->getKind();
switch (srcKind) {
case MetadataKind::Metatype: {
const Metadata *srcMetatype = *(const Metadata * const *) srcValue;
if (auto result = swift_dynamicCastMetatype(
srcMetatype, destMetatypeType->InstanceType)) {
*((const Metadata **) destLocation) = result;
return DynamicCastResult::SuccessViaCopy;
}
return DynamicCastResult::Failure;
}
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
// Some classes are actually metatypes
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If object is null, then we're in compatibility mode.
// Continuing here at all is dangerous, but that's what the
// pre-Swift-5.4 casting logic did.
if (srcObject == nullptr) {
return DynamicCastResult::Failure;
}
if (auto metatype = _getUnknownClassAsMetatype(srcObject)) {
auto srcInnerValue = reinterpret_cast<OpaqueValue *>(&metatype);
auto srcInnerType = swift_getMetatypeMetadata(metatype);
return tryCast(destLocation, destType, srcInnerValue, srcInnerType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
}
#endif
return DynamicCastResult::Failure;
}
default:
return DynamicCastResult::Failure;
}
}
/// Perform a dynamic cast of a metatype to an existential metatype type.
static DynamicCastResult
_dynamicCastMetatypeToExistentialMetatype(
OpaqueValue *destLocation, const ExistentialMetatypeMetadata *destType,
const Metadata *srcMetatype,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
// The instance type of an existential metatype must be either an
// existential or an existential metatype.
auto destMetatype
= reinterpret_cast<ExistentialMetatypeContainer *>(destLocation);
// If it's an existential, we need to check for conformances.
auto targetInstanceType = destType->InstanceType;
if (auto targetInstanceTypeAsExistential =
dyn_cast<ExistentialTypeMetadata>(targetInstanceType)) {
// Check for conformance to all the protocols.
// TODO: collect the witness tables.
const WitnessTable **conformance
= destMetatype ? destMetatype->getWitnessTables() : nullptr;
if (!_conformsToProtocols(nullptr, srcMetatype,
targetInstanceTypeAsExistential,
conformance)) {
return DynamicCastResult::Failure;
}
if (destMetatype)
destMetatype->Value = srcMetatype;
return DynamicCastResult::SuccessViaCopy;
}
// Otherwise, we're casting to SomeProtocol.Type.Type.
auto targetInstanceTypeAsMetatype =
cast<ExistentialMetatypeMetadata>(targetInstanceType);
// If the source type isn't a metatype, the cast fails.
auto srcMetatypeMetatype = dyn_cast<MetatypeMetadata>(srcMetatype);
if (!srcMetatypeMetatype) {
return DynamicCastResult::Failure;
}
// The representation of an existential metatype remains consistent
// arbitrarily deep: a metatype, followed by some protocols. The
// protocols are the same at every level, so we can just set the
// metatype correctly and then recurse, letting the recursive call
// fill in the conformance information correctly.
// Proactively set the destination metatype so that we can tail-recur,
// unless we've already done so. There's no harm in doing this even if
// the cast fails.
if (destLocation)
*((const Metadata **) destLocation) = srcMetatype;
// Recurse.
auto srcInstanceType = srcMetatypeMetatype->InstanceType;
return _dynamicCastMetatypeToExistentialMetatype(
nullptr,
targetInstanceTypeAsMetatype,
srcInstanceType,
destFailureType,
srcFailureType,
takeOnSuccess, mayDeferChecks);
}
// "ExistentialMetatype" is the metatype for an existential type.
static DynamicCastResult
tryCastToExistentialMetatype(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
assert(srcType != destType);
assert(destType->getKind() == MetadataKind::ExistentialMetatype);
auto destExistentialMetatypeType
= cast<ExistentialMetatypeMetadata>(destType);
MetadataKind srcKind = srcType->getKind();
switch (srcKind) {
case MetadataKind::Metatype: { // Metatype => ExistentialMetatype
const Metadata *srcMetatype = *(const Metadata * const *) srcValue;
return _dynamicCastMetatypeToExistentialMetatype(
destLocation,
destExistentialMetatypeType,
srcMetatype,
destFailureType,
srcFailureType,
takeOnSuccess, mayDeferChecks);
}
case MetadataKind::ObjCClassWrapper: {
// Some Obj-C classes are actually metatypes
#if SWIFT_OBJC_INTEROP
void *srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, we're in compatibility mode.
// Continuing here at al is dangerous, but that's what the
// pre-Swift-5.4 casting logic did.
if (srcObject == nullptr) {
return DynamicCastResult::Failure;
}
if (auto metatype = _getUnknownClassAsMetatype(srcObject)) {
return _dynamicCastMetatypeToExistentialMetatype(
destLocation,
destExistentialMetatypeType,
metatype,
destFailureType,
srcFailureType,
takeOnSuccess, mayDeferChecks);
}
#endif
return DynamicCastResult::Failure;
}
default:
return DynamicCastResult::Failure;
}
}
/******************************************************************************/
/********************************** Dispatch **********************************/
/******************************************************************************/
// A layer of functions that evaluate the source and/or destination types
// in order to invoke a tailored casting operation above.
//
// This layer also deals with general issues of unwrapping box types
// and invoking bridging conversions defined via the _ObjectiveCBridgeable
// protocol.
//
// Most of the caster functions above should be fairly simple:
// * They should deal with a single target type,
// * They should assume the source is fully unwrapped,
// * They should not try to report or cleanup failure,
// * If they can take, they should report the source was destroyed.
// Based on the destination type alone, select a targeted casting function.
// This design avoids some redundant inspection of the destination type
// data, for example, when we unwrap source boxes.
static tryCastFunctionType *selectCasterForDest(const Metadata *destType) {
auto destKind = destType->getKind();
switch (destKind) {
case MetadataKind::Class:
return tryCastToSwiftClass;
case MetadataKind::Struct: {
const auto targetDescriptor = cast<StructMetadata>(destType)->Description;
if (targetDescriptor == &NOMINAL_TYPE_DESCR_SYM(SS)) {
return tryCastToString;
}
if (targetDescriptor == &STRUCT_TYPE_DESCR_SYM(s11AnyHashable)) {
return tryCastToAnyHashable;
}
if (targetDescriptor == &NOMINAL_TYPE_DESCR_SYM(Sa)) {
return tryCastToArray;
}
if (targetDescriptor == &NOMINAL_TYPE_DESCR_SYM(SD)) {
return tryCastToDictionary;
}
if (targetDescriptor == &NOMINAL_TYPE_DESCR_SYM(Sh)) {
return tryCastToSet;
}
return tryCastToStruct;
}
case MetadataKind::Enum:
return tryCastToEnum;
case MetadataKind::Optional:
return tryCastToOptional;
case MetadataKind::ForeignClass:
return tryCastToForeignClass;
case MetadataKind::Opaque:
return tryCastToOpaque;
case MetadataKind::Tuple:
return tryCastToTuple;
case MetadataKind::Function:
return tryCastToFunction;
case MetadataKind::Existential: {
auto existentialType = cast<ExistentialTypeMetadata>(destType);
switch (existentialType->getRepresentation()) {
case ExistentialTypeRepresentation::Opaque:
if (existentialType->NumProtocols == 0) {
return tryCastToUnconstrainedOpaqueExistential; // => Unconstrained Any
} else {
return tryCastToConstrainedOpaqueExistential; // => Non-class-constrained protocol
}
case ExistentialTypeRepresentation::Class:
return tryCastToClassExistential; // => AnyObject, with or without protocol constraints
case ExistentialTypeRepresentation::Error: // => Error existential
return tryCastToErrorExistential;
}
swift_unreachable(
"Unknown existential type representation in dynamic cast dispatch");
}
case MetadataKind::ExtendedExistential:
return tryCastToExtendedExistential;
case MetadataKind::Metatype:
return tryCastToMetatype;
case MetadataKind::ObjCClassWrapper:
return tryCastToObjectiveCClass;
case MetadataKind::ExistentialMetatype:
return tryCastToExistentialMetatype;
case MetadataKind::HeapLocalVariable:
case MetadataKind::HeapGenericLocalVariable:
case MetadataKind::ErrorObject:
// These are internal details of runtime-only structures,
// so will never appear in compiler-generated types.
// As such, they don't need support here.
swift_unreachable(
"Unexpected MetadataKind in dynamic cast dispatch");
return nullptr;
default:
// If you see this message, then there is a new MetadataKind that I didn't
// know about when I wrote this code. Please figure out what it is, how to
// handle it, and add a case for it.
swift_unreachable(
"Unknown MetadataKind in dynamic cast dispatch");
}
}
// This top-level driver provides the general flow for all casting
// operations. It recursively unwraps source and destination as it
// searches for a suitable conversion.
static DynamicCastResult
tryCast(
OpaqueValue *destLocation, const Metadata *destType,
OpaqueValue *srcValue, const Metadata *srcType,
const Metadata *&destFailureType, const Metadata *&srcFailureType,
bool takeOnSuccess, bool mayDeferChecks)
{
destFailureType = destType;
srcFailureType = srcType;
////////////////////////////////////////////////////////////////////////
//
// 1. If types match exactly, we can just move/copy the data.
// (The tryCastToXyz functions never see this trivial case.)
//
if (srcType == destType) {
if (takeOnSuccess) {
destType->vw_initializeWithTake(destLocation, srcValue);
return DynamicCastResult::SuccessViaTake;
} else {
destType->vw_initializeWithCopy(destLocation, srcValue);
return DynamicCastResult::SuccessViaCopy;
}
}
auto destKind = destType->getKind();
auto srcKind = srcType->getKind();
////////////////////////////////////////////////////////////////////////
//
// 2. Try directly casting the current srcValue to the target type.
// (If the dynamic type is different, try that too.)
//
auto tryCastToDestType = selectCasterForDest(destType);
if (tryCastToDestType == nullptr) {
return DynamicCastResult::Failure;
}
auto castResult = tryCastToDestType(destLocation, destType, srcValue,
srcType, destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(castResult)) {
return castResult;
}
if (srcKind == MetadataKind::Class
|| srcKind == MetadataKind::ObjCClassWrapper
|| srcKind == MetadataKind::ForeignClass) {
auto srcObject = getNonNullSrcObject(srcValue, srcType, destType);
// If srcObject is null, we're in compatibility mode.
// But we can't lookup dynamic type for a null class reference, so
// just skip this in that case.
if (srcObject != nullptr) {
auto srcDynamicType = swift_getObjectType(srcObject);
if (srcDynamicType != srcType) {
srcFailureType = srcDynamicType;
auto castResult = tryCastToDestType(
destLocation, destType, srcValue, srcDynamicType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(castResult)) {
return castResult;
}
}
}
}
////////////////////////////////////////////////////////////////////////
//
// 3. Try recursively unwrapping _source_ boxes, including
// existentials, AnyHashable, SwiftValue, and Error.
//
switch (srcKind) {
case MetadataKind::Class: {
#if !SWIFT_OBJC_INTEROP
// Try unwrapping native __SwiftValue implementation
auto subcastResult = tryCastUnwrappingSwiftValueSource(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
#endif
break;
}
case MetadataKind::ObjCClassWrapper: {
#if SWIFT_OBJC_INTEROP
// Try unwrapping Obj-C __SwiftValue implementation
auto subcastResult = tryCastUnwrappingObjCSwiftValueSource(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
#endif
#if SWIFT_OBJC_INTEROP
// Try unwrapping Obj-C NSError container
auto innerFlags = DynamicCastFlags::Default;
if (tryDynamicCastNSErrorToValue(
destLocation, srcValue, srcType, destType, innerFlags)) {
return DynamicCastResult::SuccessViaCopy;
}
#endif
break;
}
case MetadataKind::Struct: {
auto srcStructType = cast<StructMetadata>(srcType);
auto srcStructDescription = srcStructType->getDescription();
// Try unwrapping AnyHashable container
if (srcStructDescription == &STRUCT_TYPE_DESCR_SYM(s11AnyHashable)) {
if (_swift_anyHashableDownCastConditionalIndirect(
srcValue, destLocation, destType)) {
return DynamicCastResult::SuccessViaCopy;
}
}
break;
}
case MetadataKind::Existential: {
auto subcastResult = tryCastUnwrappingExistentialSource(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
break;
}
case MetadataKind::ExistentialMetatype: {
auto subcastResult = tryCastUnwrappingExistentialMetatypeSource(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
break;
}
case MetadataKind::ExtendedExistential: {
auto subcastResult = tryCastUnwrappingExtendedExistentialSource(
destLocation, destType, srcValue, srcType, destFailureType,
srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
break;
}
default:
break;
}
////////////////////////////////////////////////////////////////////////
//
// 4. Try recursively unwrapping Optionals. First try jointly unwrapping
// both source and destination, then just destination, then just source.
// Note that if both are optional, we try all three of these!
// For example, consider casting an Optional<T> to
// Optional<CustomDebugStringConvertible>. If T conforms, we need to
// unwrap both. But if it doesn't, we unwrap just the destination
// in order to cast Optional<T> to the protocol directly.
//
if (destKind == MetadataKind::Optional) {
if (srcKind == MetadataKind::Optional) {
auto subcastResult = tryCastUnwrappingOptionalBoth(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
}
auto subcastResult = tryCastUnwrappingOptionalDestination(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
}
if (srcKind == MetadataKind::Optional) {
auto subcastResult = tryCastUnwrappingOptionalSource(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
}
////////////////////////////////////////////////////////////////////////
//
// 5. Finally, explore bridging conversions via ObjectiveCBridgeable,
// Error, and __SwiftValue boxing.
//
switch (destKind) {
case MetadataKind::Optional: {
// Optional supports _ObjectiveCBridgeable from an unconstrained AnyObject
if (srcType->getKind() == MetadataKind::Existential) {
auto srcExistentialType = cast<ExistentialTypeMetadata>(srcType);
if ((srcExistentialType->getRepresentation() == ExistentialTypeRepresentation::Class)
&& (srcExistentialType->NumProtocols == 0)
&& (srcExistentialType->getSuperclassConstraint() == nullptr)
&& (srcExistentialType->isClassBounded())) {
auto toObjCResult = tryCastFromClassToObjCBridgeable(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, false);
if (isSuccess(toObjCResult)) {
return toObjCResult;
}
}
}
break;
}
case MetadataKind::Existential: {
// Try general machinery for stuffing values into AnyObject:
auto destExistentialType = cast<ExistentialTypeMetadata>(destType);
if (destExistentialType->getRepresentation() == ExistentialTypeRepresentation::Class) {
// Some types have custom Objective-C bridging support...
auto subcastResult = tryCastFromObjCBridgeableToClass(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
// Other types can be boxed into a __SwiftValue container...
auto swiftValueCastResult = tryCastToClassExistentialViaSwiftValue(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(swiftValueCastResult)) {
return swiftValueCastResult;
}
}
break;
}
case MetadataKind::Class:
case MetadataKind::ObjCClassWrapper:
case MetadataKind::ForeignClass: {
// Try _ObjectiveCBridgeable to bridge _to_ a class type _from_ a
// struct/enum type. Note: Despite the name, this is used for both
// Swift-Swift and Swift-ObjC bridging
if (srcKind == MetadataKind::Struct || srcKind == MetadataKind::Enum) {
auto subcastResult = tryCastFromObjCBridgeableToClass(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
}
#if SWIFT_OBJC_INTEROP
if (destKind == MetadataKind::ObjCClassWrapper) {
// If the destination type is an NSError or NSObject, and the source type
// is an Error, then the cast might succeed by NSError bridging.
if (auto srcErrorWitness = findErrorWitness(srcType)) {
if (destType == getNSErrorMetadata()
|| destType == getNSObjectMetadata()) {
auto flags = DynamicCastFlags::Default;
auto error = dynamicCastValueToNSError(srcValue, srcType,
srcErrorWitness, flags);
*reinterpret_cast<id *>(destLocation) = error;
return DynamicCastResult::SuccessViaCopy;
}
}
}
#endif
break;
}
case MetadataKind::Struct:
case MetadataKind::Enum: {
// Use _ObjectiveCBridgeable to bridge _from_ a class type _to_ a
// struct/enum type. Note: Despite the name, this is used for both
// Swift-Swift and ObjC-Swift bridging
if (srcKind == MetadataKind::Class
|| srcKind == MetadataKind::ObjCClassWrapper
|| srcKind == MetadataKind::ForeignClass) {
auto subcastResult = tryCastFromClassToObjCBridgeable(
destLocation, destType, srcValue, srcType,
destFailureType, srcFailureType, takeOnSuccess, mayDeferChecks);
if (isSuccess(subcastResult)) {
return subcastResult;
}
}
// Note: In theory, if src and dest are both struct/enum types, we could see
// if the ObjC bridgeable class types matched and then do a two-step
// conversion from src -> bridge class -> dest. Such ambitious conversions
// might cause more harm than good, though. In particular, it could
// undermine code that uses a series of `as?` to quickly determine how to
// handle a particular object.
break;
}
default:
break;
}
return DynamicCastResult::Failure;
}
/******************************************************************************/
/****************************** Main Entrypoint *******************************/
/******************************************************************************/
/// ABI: Perform a dynamic cast to an arbitrary type.
static bool
swift_dynamicCastImpl(OpaqueValue *destLocation,
OpaqueValue *srcValue,
const Metadata *srcType,
const Metadata *destType,
DynamicCastFlags flags)
{
// If the compiler has asked for a "take", we can
// move pointers without ref-counting overhead.
bool takeOnSuccess = flags & DynamicCastFlags::TakeOnSuccess;
// Unconditional casts are allowed to crash the program on failure.
// We can exploit that for performance: return a partial conversion
// immediately and do additional checks lazily when the results are
// actually accessed.
bool mayDeferChecks = flags & DynamicCastFlags::Unconditional;
// Attempt the cast...
const Metadata *destFailureType = destType;
const Metadata *srcFailureType = srcType;
auto result = tryCast(
destLocation, destType,
srcValue, srcType,
destFailureType, srcFailureType,
takeOnSuccess, mayDeferChecks);
switch (result) {
case DynamicCastResult::Failure:
if (flags & DynamicCastFlags::Unconditional) {
swift_dynamicCastFailure(srcFailureType, destFailureType);
}
if (flags & DynamicCastFlags::DestroyOnFailure) {
srcType->vw_destroy(srcValue);
}
return false;
case DynamicCastResult::SuccessViaCopy:
if (takeOnSuccess) { // We copied, but compiler asked for take.
srcType->vw_destroy(srcValue);
}
return true;
case DynamicCastResult::SuccessViaTake:
return true;
}
}
#define OVERRIDE_DYNAMICCASTING COMPATIBILITY_OVERRIDE
#include COMPATIBILITY_OVERRIDE_INCLUDE_PATH
|