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
|
//===--- TypeRef.cpp - Swift Type References for Reflection ---------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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
//
//===----------------------------------------------------------------------===//
//
// Implements the structures of type references for property and enum
// case reflection.
//
//===----------------------------------------------------------------------===//
#if SWIFT_ENABLE_REFLECTION
#include "swift/Basic/Range.h"
#include "swift/Demangling/Demangle.h"
#include "swift/RemoteInspection/TypeRef.h"
#include "swift/RemoteInspection/TypeRefBuilder.h"
#include <iostream>
using namespace swift;
using namespace reflection;
class PrintTypeRef : public TypeRefVisitor<PrintTypeRef, void> {
std::ostream &stream;
unsigned Indent;
std::ostream &indent(unsigned Amount) {
for (unsigned i = 0; i < Amount; ++i)
stream << " ";
return stream;
}
std::ostream &printHeader(std::string Name) {
indent(Indent) << "(" << Name;
return stream;
}
std::ostream &printField(std::string name, std::string value) {
if (!name.empty())
stream << " " << name << "=" << value;
else
stream << " " << value;
return stream;
}
void printRec(const TypeRef *typeRef) {
stream << "\n";
Indent += 2;
visit(typeRef);
Indent -= 2;
}
public:
PrintTypeRef(std::ostream &stream, unsigned Indent)
: stream(stream), Indent(Indent) {}
void visitBuiltinTypeRef(const BuiltinTypeRef *B) {
printHeader("builtin");
auto demangled = Demangle::demangleTypeAsString(B->getMangledName());
printField("", demangled);
stream << ")";
}
void visitNominalTypeRef(const NominalTypeRef *N) {
StringRef mangledName = N->getMangledName();
if (N->isStruct())
printHeader("struct");
else if (N->isEnum())
printHeader("enum");
else if (N->isClass())
printHeader("class");
else if (N->isProtocol()) {
printHeader("protocol");
mangledName = Demangle::dropSwiftManglingPrefix(mangledName);
} else if (N->isAlias())
printHeader("alias");
else
printHeader("nominal");
auto demangled = Demangle::demangleTypeAsString(mangledName);
printField("", demangled);
if (auto parent = N->getParent())
printRec(parent);
stream << ")";
}
void visitBoundGenericTypeRef(const BoundGenericTypeRef *BG) {
if (BG->isStruct())
printHeader("bound_generic_struct");
else if (BG->isEnum())
printHeader("bound_generic_enum");
else if (BG->isClass())
printHeader("bound_generic_class");
else
printHeader("bound_generic");
auto demangled = Demangle::demangleTypeAsString(BG->getMangledName());
printField("", demangled);
for (auto param : BG->getGenericParams())
printRec(param);
if (auto parent = BG->getParent())
printRec(parent);
stream << ")";
}
void visitTupleTypeRef(const TupleTypeRef *T) {
printHeader("tuple");
auto Labels = T->getLabels();
for (auto NameElement : llvm::zip_first(Labels, T->getElements())) {
auto Label = std::get<0>(NameElement);
if (!Label.empty())
stream << Label << " = ";
printRec(std::get<1>(NameElement));
}
stream << ")";
}
void visitFunctionTypeRef(const FunctionTypeRef *F) {
printHeader("function");
switch (F->getFlags().getConvention()) {
case FunctionMetadataConvention::Swift:
break;
case FunctionMetadataConvention::Block:
printField("convention", "block");
break;
case FunctionMetadataConvention::Thin:
printField("convention", "thin");
break;
case FunctionMetadataConvention::CFunctionPointer:
printField("convention", "c");
break;
}
switch (F->getDifferentiabilityKind().Value) {
case FunctionMetadataDifferentiabilityKind::NonDifferentiable:
break;
case FunctionMetadataDifferentiabilityKind::Forward:
printField("differentiable", "forward");
break;
case FunctionMetadataDifferentiabilityKind::Reverse:
printField("differentiable", "reverse");
break;
case FunctionMetadataDifferentiabilityKind::Normal:
printField("differentiable", "normal");
break;
case FunctionMetadataDifferentiabilityKind::Linear:
printField("differentiable", "linear");
break;
}
if (auto globalActor = F->getGlobalActor()) {
stream << "\n";
Indent += 2;
printHeader("global-actor");
{
Indent += 2;
printRec(globalActor);
stream << ")";
Indent -= 2;
}
Indent += 2;
}
if (F->getExtFlags().isIsolatedAny()) {
printField("isolated", "any");
}
if (F->getExtFlags().hasSendingResult()) {
printField("", "sending-result");
}
stream << "\n";
Indent += 2;
printHeader("parameters");
auto ¶meters = F->getParameters();
for (const auto ¶m : parameters) {
auto flags = param.getFlags();
if (!flags.isNone()) {
Indent += 2;
stream << "\n";
}
switch (flags.getOwnership()) {
case ParameterOwnership::Default:
/* nothing */
break;
case ParameterOwnership::InOut:
printHeader("inout");
break;
case ParameterOwnership::Shared:
printHeader("shared");
break;
case ParameterOwnership::Owned:
printHeader("owned");
break;
}
if (flags.isIsolated())
printHeader("isolated");
if (flags.isVariadic())
printHeader("variadic");
if (flags.isSending())
printHeader("sending");
printRec(param.getType());
if (!flags.isNone()) {
Indent -= 2;
stream << ")";
}
}
if (parameters.empty())
stream << ")";
stream << "\n";
printHeader("result");
printRec(F->getResult());
stream << ")";
Indent -= 2;
}
void visitProtocolCompositionTypeRef(const ProtocolCompositionTypeRef *PC) {
printHeader("protocol_composition");
if (PC->hasExplicitAnyObject())
stream << " any_object";
if (auto superclass = PC->getSuperclass())
printRec(superclass);
for (auto protocol : PC->getProtocols())
printRec(protocol);
stream << ")";
}
void
visitConstrainedExistentialTypeRef(const ConstrainedExistentialTypeRef *CET) {
printHeader("constrained_existential_type");
printRec(CET->getBase());
for (auto req : CET->getRequirements())
visitTypeRefRequirement(req);
stream << ")";
}
void visitMetatypeTypeRef(const MetatypeTypeRef *M) {
printHeader("metatype");
if (M->wasAbstract())
printField("", "was_abstract");
printRec(M->getInstanceType());
stream << ")";
}
void visitExistentialMetatypeTypeRef(const ExistentialMetatypeTypeRef *EM) {
printHeader("existential_metatype");
printRec(EM->getInstanceType());
stream << ")";
}
void
visitGenericTypeParameterTypeRef(const GenericTypeParameterTypeRef *GTP) {
printHeader("generic_type_parameter");
printField("depth", std::to_string(GTP->getDepth()));
printField("index", std::to_string(GTP->getIndex()));
stream << ")";
}
void visitDependentMemberTypeRef(const DependentMemberTypeRef *DM) {
printHeader("dependent_member");
printField("protocol", DM->getProtocol());
printRec(DM->getBase());
printField("member", DM->getMember());
stream << ")";
}
void visitForeignClassTypeRef(const ForeignClassTypeRef *F) {
printHeader("foreign");
if (!F->getName().empty())
printField("name", F->getName());
stream << ")";
}
void visitObjCClassTypeRef(const ObjCClassTypeRef *OC) {
printHeader("objective_c_class");
if (!OC->getName().empty())
printField("name", OC->getName());
stream << ")";
}
void visitObjCProtocolTypeRef(const ObjCProtocolTypeRef *OC) {
printHeader("objective_c_protocol");
if (!OC->getName().empty())
printField("name", OC->getName());
stream << ")";
}
#define REF_STORAGE(Name, name, ...) \
void visit##Name##StorageTypeRef(const Name##StorageTypeRef *US) { \
printHeader(#name "_storage"); \
printRec(US->getType()); \
stream << ")"; \
}
#include "swift/AST/ReferenceStorage.def"
void visitSILBoxTypeRef(const SILBoxTypeRef *SB) {
printHeader("sil_box");
printRec(SB->getBoxedType());
stream << ")";
}
void visitTypeRefRequirement(const TypeRefRequirement &req) {
printHeader("requirement ");
switch (req.getKind()) {
case RequirementKind::SameShape:
printRec(req.getFirstType());
stream << ".shape == ";
printRec(req.getSecondType());
stream << ".shape";
break;
case RequirementKind::Conformance:
case RequirementKind::Superclass:
printRec(req.getFirstType());
stream << " : ";
printRec(req.getSecondType());
break;
case RequirementKind::SameType:
printRec(req.getFirstType());
stream << " == ";
printRec(req.getSecondType());
break;
case RequirementKind::Layout:
stream << "layout requirement";
break;
}
stream << ")";
}
void visitSILBoxTypeWithLayoutTypeRef(const SILBoxTypeWithLayoutTypeRef *SB) {
printHeader("sil_box_with_layout\n");
Indent += 2;
printHeader("layout\n");
Indent += 2;
for (auto &f : SB->getFields()) {
printHeader(f.isMutable() ? "var" : "let");
printRec(f.getType());
stream << ")";
}
Indent -= 2;
stream << ")\n";
printHeader("generic_signature\n");
Indent += 2;
for (auto &subst : SB->getSubstitutions()) {
printHeader("substitution");
printRec(subst.first);
printRec(subst.second);
stream << ")";
}
Indent -= 2;
for (auto &req : SB->getRequirements()) {
visitTypeRefRequirement(req);
}
stream << ")";
stream << ")";
}
void visitOpaqueArchetypeTypeRef(const OpaqueArchetypeTypeRef *O) {
printHeader("opaque_archetype");
printField("id", O->getID().str());
printField("description", O->getDescription().str());
stream << " ordinal " << O->getOrdinal() << " ";
for (auto argList : O->getArgumentLists()) {
stream << "\n";
indent(Indent + 2) << "args: <";
for (auto arg : argList) {
printRec(arg);
}
stream << ">";
}
stream << ")";
}
void visitOpaqueTypeRef(const OpaqueTypeRef *O) {
printHeader("opaque");
stream << ")";
}
};
struct TypeRefIsConcrete
: public TypeRefVisitor<TypeRefIsConcrete, bool> {
const GenericArgumentMap &Subs;
TypeRefIsConcrete(const GenericArgumentMap &Subs) : Subs(Subs) {}
bool visitBuiltinTypeRef(const BuiltinTypeRef *B) {
return true;
}
bool visitNominalTypeRef(const NominalTypeRef *N) {
if (N->getParent())
return visit(N->getParent());
return true;
}
bool visitBoundGenericTypeRef(const BoundGenericTypeRef *BG) {
if (BG->getParent())
if (!visit(BG->getParent()))
return false;
for (auto Param : BG->getGenericParams())
if (!visit(Param))
return false;
return true;
}
bool visitTupleTypeRef(const TupleTypeRef *T) {
for (auto Element : T->getElements()) {
if (!visit(Element))
return false;
}
return true;
}
bool visitFunctionTypeRef(const FunctionTypeRef *F) {
for (const auto &Param : F->getParameters())
if (!visit(Param.getType()))
return false;
return visit(F->getResult());
}
bool
visitProtocolCompositionTypeRef(const ProtocolCompositionTypeRef *PC) {
for (auto Protocol : PC->getProtocols())
if (!visit(Protocol))
return false;
if (auto Superclass = PC->getSuperclass())
if (!visit(Superclass))
return false;
return true;
}
bool
visitConstrainedExistentialTypeRef(const ConstrainedExistentialTypeRef *CET) {
return visit(CET->getBase());
}
bool visitMetatypeTypeRef(const MetatypeTypeRef *M) {
return visit(M->getInstanceType());
}
bool
visitExistentialMetatypeTypeRef(const ExistentialMetatypeTypeRef *EM) {
return visit(EM->getInstanceType());
}
bool
visitGenericTypeParameterTypeRef(const GenericTypeParameterTypeRef *GTP) {
return Subs.find({GTP->getDepth(), GTP->getIndex()}) != Subs.end();
}
bool
visitDependentMemberTypeRef(const DependentMemberTypeRef *DM) {
return visit(DM->getBase());
}
bool visitForeignClassTypeRef(const ForeignClassTypeRef *F) {
return true;
}
bool visitObjCClassTypeRef(const ObjCClassTypeRef *OC) {
return true;
}
bool visitObjCProtocolTypeRef(const ObjCProtocolTypeRef *OC) {
return true;
}
bool visitOpaqueTypeRef(const OpaqueTypeRef *O) {
return true;
}
bool visitOpaqueArchetypeTypeRef(const OpaqueArchetypeTypeRef *O) {
return false;
}
#define REF_STORAGE(Name, name, ...) \
bool visit##Name##StorageTypeRef(const Name##StorageTypeRef *US) { \
return visit(US->getType()); \
}
#include "swift/AST/ReferenceStorage.def"
bool visitSILBoxTypeRef(const SILBoxTypeRef *SB) {
return visit(SB->getBoxedType());
}
bool visitSILBoxTypeWithLayoutTypeRef(const SILBoxTypeWithLayoutTypeRef *SB) {
return true;
}
};
const OpaqueTypeRef *
OpaqueTypeRef::Singleton = new OpaqueTypeRef();
const OpaqueTypeRef *OpaqueTypeRef::get() {
return Singleton;
}
void TypeRef::dump() const { dump(std::cerr); }
void TypeRef::dump(std::ostream &stream, unsigned Indent) const {
PrintTypeRef(stream, Indent).visit(this);
stream << "\n";
}
class DemanglingForTypeRef
: public TypeRefVisitor<DemanglingForTypeRef, Demangle::NodePointer> {
Demangle::Demangler &Dem;
/// Demangle a type and dive into the outermost Type node.
Demangle::NodePointer demangleAndUnwrapType(llvm::StringRef mangledName) {
auto node = Dem.demangleType(mangledName);
if (node && node->getKind() == Node::Kind::Type && node->getNumChildren())
node = node->getFirstChild();
return node;
}
public:
DemanglingForTypeRef(Demangle::Demangler &Dem) : Dem(Dem) {}
Demangle::NodePointer visit(const TypeRef *typeRef) {
auto node = TypeRefVisitor<DemanglingForTypeRef,
Demangle::NodePointer>::visit(typeRef);
if (!node)
return nullptr;
// Wrap all nodes in a Type node, as consumers generally expect.
auto typeNode = Dem.createNode(Node::Kind::Type);
typeNode->addChild(node, Dem);
return typeNode;
}
Demangle::NodePointer visitBuiltinTypeRef(const BuiltinTypeRef *B) {
return demangleAndUnwrapType(B->getMangledName());
}
Demangle::NodePointer visitNominalTypeRef(const NominalTypeRef *N) {
auto node = demangleAndUnwrapType(N->getMangledName());
if (!node || node->getNumChildren() != 2)
return node;
auto parent = N->getParent();
if (!parent)
return node;
// Swap in the richer parent that is stored in the NominalTypeRef
// instead of what is encoded in the mangled name. The mangled name's
// context has been "unspecialized" by NodeBuilder.
auto parentNode = visit(parent);
if (!parentNode)
return node;
if (parentNode->getKind() == Node::Kind::Type &&
parentNode->getNumChildren())
parentNode = parentNode->getFirstChild();
auto contextualizedNode = Dem.createNode(node->getKind());
contextualizedNode->addChild(parentNode, Dem);
contextualizedNode->addChild(node->getChild(1), Dem);
return contextualizedNode;
}
Demangle::NodePointer
visitBoundGenericTypeRef(const BoundGenericTypeRef *BG) {
Node::Kind genericNodeKind;
if (BG->isStruct()) {
genericNodeKind = Node::Kind::BoundGenericStructure;
} else if (BG->isEnum()) {
genericNodeKind = Node::Kind::BoundGenericEnum;
} else if (BG->isClass()) {
genericNodeKind = Node::Kind::BoundGenericClass;
} else {
genericNodeKind = Node::Kind::BoundGenericOtherNominalType;
}
auto unspecializedType = Dem.demangleType(BG->getMangledName());
auto genericArgsList = Dem.createNode(Node::Kind::TypeList);
for (auto param : BG->getGenericParams())
genericArgsList->addChild(visit(param), Dem);
auto genericNode = Dem.createNode(genericNodeKind);
genericNode->addChild(unspecializedType, Dem);
genericNode->addChild(genericArgsList, Dem);
auto parent = BG->getParent();
if (!parent)
return genericNode;
auto parentNode = visit(parent);
if (!parentNode || !parentNode->hasChildren() ||
parentNode->getKind() != Node::Kind::Type ||
!unspecializedType->hasChildren())
return genericNode;
// Peel off the "Type" node.
parentNode = parentNode->getFirstChild();
auto nominalNode = unspecializedType->getFirstChild();
if (nominalNode->getNumChildren() != 2)
return genericNode;
// Save identifier for reinsertion later, we have to remove it
// so we can insert the parent node as the first child.
auto identifierNode = nominalNode->getLastChild();
// Remove all children.
nominalNode->removeChildAt(1);
nominalNode->removeChildAt(0);
// Add the parent we just visited back in, followed by the identifier.
nominalNode->addChild(parentNode, Dem);
nominalNode->addChild(identifierNode, Dem);
return genericNode;
}
Demangle::NodePointer visitTupleTypeRef(const TupleTypeRef *T) {
auto tuple = Dem.createNode(Node::Kind::Tuple);
auto Labels = T->getLabels();
for (auto LabelElement : llvm::zip(Labels, T->getElements())) {
auto tupleElt = Dem.createNode(Node::Kind::TupleElement);
auto Label = std::get<0>(LabelElement);
if (!Label.empty()) {
auto name = Dem.createNode(Node::Kind::TupleElementName, Label);
tupleElt->addChild(name, Dem);
}
tupleElt->addChild(visit(std::get<1>(LabelElement)), Dem);
tuple->addChild(tupleElt, Dem);
}
return tuple;
}
Demangle::NodePointer visitFunctionTypeRef(const FunctionTypeRef *F) {
Node::Kind kind;
switch (F->getFlags().getConvention()) {
case FunctionMetadataConvention::Swift:
kind = !F->getFlags().isEscaping() ? Node::Kind::NoEscapeFunctionType
: Node::Kind::FunctionType;
break;
case FunctionMetadataConvention::Block:
kind = Node::Kind::ObjCBlock;
break;
case FunctionMetadataConvention::Thin:
kind = Node::Kind::ThinFunctionType;
break;
case FunctionMetadataConvention::CFunctionPointer:
kind = Node::Kind::CFunctionPointer;
break;
}
llvm::SmallVector<std::pair<NodePointer, bool>, 8> inputs;
for (const auto ¶m : F->getParameters()) {
auto flags = param.getFlags();
auto input = visit(param.getType());
auto wrapInput = [&](Node::Kind kind) {
auto parent = Dem.createNode(kind);
parent->addChild(input, Dem);
input = parent;
};
if (flags.isNoDerivative()) {
wrapInput(Node::Kind::NoDerivative);
}
switch (flags.getOwnership()) {
case ParameterOwnership::Default:
/* nothing */
break;
case ParameterOwnership::InOut:
wrapInput(Node::Kind::InOut);
break;
case ParameterOwnership::Shared:
wrapInput(Node::Kind::Shared);
break;
case ParameterOwnership::Owned:
wrapInput(Node::Kind::Owned);
break;
}
if (flags.isIsolated()) {
wrapInput(Node::Kind::Isolated);
}
if (flags.isSending()) {
wrapInput(Node::Kind::Sending);
}
inputs.push_back({input, flags.isVariadic()});
}
NodePointer totalInput = nullptr;
// FIXME: this is copy&paste from Demangle.cpp
switch (inputs.size()) {
case 1: {
auto singleParam = inputs.front();
// If the sole unlabeled parameter has a non-tuple type, encode
// the parameter list as a single type.
if (!singleParam.second) {
auto singleType = singleParam.first;
if (singleType->getKind() == Node::Kind::Type)
singleType = singleType->getFirstChild();
if (singleType->getKind() != Node::Kind::Tuple) {
totalInput = singleParam.first;
break;
}
}
// Otherwise it requires a tuple wrapper.
SWIFT_FALLTHROUGH;
}
// This covers both none and multiple parameters.
default:
auto tuple = Dem.createNode(Node::Kind::Tuple);
for (auto &input : inputs) {
NodePointer eltType;
bool isVariadic;
std::tie(eltType, isVariadic) = input;
// Tuple element := variadic-marker label? type
auto tupleElt = Dem.createNode(Node::Kind::TupleElement);
if (isVariadic)
tupleElt->addChild(Dem.createNode(Node::Kind::VariadicMarker), Dem);
if (eltType->getKind() == Node::Kind::Type) {
tupleElt->addChild(eltType, Dem);
} else {
auto type = Dem.createNode(Node::Kind::Type);
type->addChild(eltType, Dem);
tupleElt->addChild(type, Dem);
}
tuple->addChild(tupleElt, Dem);
}
totalInput = tuple;
break;
}
NodePointer parameters = Dem.createNode(Node::Kind::ArgumentTuple);
NodePointer paramType = Dem.createNode(Node::Kind::Type);
paramType->addChild(totalInput, Dem);
parameters->addChild(paramType, Dem);
NodePointer resultTy = visit(F->getResult());
NodePointer result = Dem.createNode(Node::Kind::ReturnType);
result->addChild(resultTy, Dem);
auto funcNode = Dem.createNode(kind);
if (auto globalActor = F->getGlobalActor()) {
auto node = Dem.createNode(Node::Kind::GlobalActorFunctionType);
auto globalActorNode = visit(globalActor);
node->addChild(globalActorNode, Dem);
funcNode->addChild(node, Dem);
} else if (F->getExtFlags().isIsolatedAny()) {
auto node = Dem.createNode(Node::Kind::IsolatedAnyFunctionType);
funcNode->addChild(node, Dem);
} else if (F->getExtFlags().hasSendingResult()) {
auto node = Dem.createNode(Node::Kind::SendingResultFunctionType);
funcNode->addChild(node, Dem);
}
if (F->getFlags().isDifferentiable()) {
MangledDifferentiabilityKind mangledKind;
switch (F->getDifferentiabilityKind().Value) {
#define CASE(X) case FunctionMetadataDifferentiabilityKind::X: \
mangledKind = MangledDifferentiabilityKind::X; break;
CASE(NonDifferentiable)
CASE(Forward)
CASE(Reverse)
CASE(Normal)
CASE(Linear)
#undef CASE
}
funcNode->addChild(
Dem.createNode(
Node::Kind::DifferentiableFunctionType,
(Node::IndexType)mangledKind),
Dem);
}
if (F->getFlags().isThrowing()) {
if (auto thrownError = F->getThrownError()) {
auto node = Dem.createNode(Node::Kind::TypedThrowsAnnotation);
auto thrownErrorNode = visit(thrownError);
node->addChild(thrownErrorNode, Dem);
funcNode->addChild(node, Dem);
} else {
funcNode->addChild(Dem.createNode(Node::Kind::ThrowsAnnotation), Dem);
}
}
if (F->getFlags().isSendable()) {
funcNode->addChild(
Dem.createNode(Node::Kind::ConcurrentFunctionType), Dem);
}
if (F->getFlags().isAsync())
funcNode->addChild(Dem.createNode(Node::Kind::AsyncAnnotation), Dem);
funcNode->addChild(parameters, Dem);
funcNode->addChild(result, Dem);
return funcNode;
}
Demangle::NodePointer
visitProtocolCompositionTypeRef(const ProtocolCompositionTypeRef *PC) {
auto type_list = Dem.createNode(Node::Kind::TypeList);
for (auto protocol : PC->getProtocols())
type_list->addChild(visit(protocol), Dem);
auto proto_list = Dem.createNode(Node::Kind::ProtocolList);
proto_list->addChild(type_list, Dem);
auto node = proto_list;
if (auto superclass = PC->getSuperclass()) {
node = Dem.createNode(Node::Kind::ProtocolListWithClass);
node->addChild(proto_list, Dem);
node->addChild(visit(superclass), Dem);
} else if (PC->hasExplicitAnyObject()) {
node = Dem.createNode(Node::Kind::ProtocolListWithAnyObject);
node->addChild(proto_list, Dem);
}
return node;
}
Demangle::NodePointer
visitConstrainedExistentialTypeRef(const ConstrainedExistentialTypeRef *CET) {
auto node = Dem.createNode(Node::Kind::ConstrainedExistential);
node->addChild(visit(CET->getBase()), Dem);
auto constraintList =
Dem.createNode(Node::Kind::ConstrainedExistentialRequirementList);
for (auto req : CET->getRequirements())
constraintList->addChild(visitTypeRefRequirement(req), Dem);
node->addChild(constraintList, Dem);
return node;
}
Demangle::NodePointer visitMetatypeTypeRef(const MetatypeTypeRef *M) {
auto node = Dem.createNode(Node::Kind::Metatype);
// FIXME: This is lossy. @objc_metatype is also abstract.
auto repr = Dem.createNode(Node::Kind::MetatypeRepresentation,
M->wasAbstract() ? "@thick" : "@thin");
node->addChild(repr, Dem);
node->addChild(visit(M->getInstanceType()), Dem);
return node;
}
Demangle::NodePointer
visitExistentialMetatypeTypeRef(const ExistentialMetatypeTypeRef *EM) {
auto node = Dem.createNode(Node::Kind::Metatype);
node->addChild(visit(EM->getInstanceType()), Dem);
return node;
}
Demangle::NodePointer
visitGenericTypeParameterTypeRef(const GenericTypeParameterTypeRef *GTP) {
auto node = Dem.createNode(Node::Kind::DependentGenericParamType);
node->addChild(Dem.createNode(Node::Kind::Index, GTP->getDepth()), Dem);
node->addChild(Dem.createNode(Node::Kind::Index, GTP->getIndex()), Dem);
return node;
}
Demangle::NodePointer
visitDependentMemberTypeRef(const DependentMemberTypeRef *DM) {
auto node = Dem.createNode(Node::Kind::DependentMemberType);
auto Base = visit(DM->getBase());
node->addChild(Base, Dem);
auto MemberId = Dem.createNode(Node::Kind::Identifier, DM->getMember());
auto MangledProtocol = DM->getProtocol();
if (MangledProtocol.empty()) {
// If there's no protocol, add the Member as an Identifier node
node->addChild(MemberId, Dem);
} else {
// Otherwise, build up a DependentAssociatedTR node with
// the member Identifer and protocol
auto AssocTy = Dem.createNode(Node::Kind::DependentAssociatedTypeRef);
AssocTy->addChild(MemberId, Dem);
auto Proto = Dem.demangleType(MangledProtocol);
assert(Proto && "Failed to demangle");
assert(Proto->getKind() == Node::Kind::Type && "Protocol type is not a type?!");
AssocTy->addChild(Proto, Dem);
node->addChild(AssocTy, Dem);
}
return node;
}
Demangle::NodePointer visitForeignClassTypeRef(const ForeignClassTypeRef *F) {
return demangleAndUnwrapType(F->getName());
}
Demangle::NodePointer visitObjCClassTypeRef(const ObjCClassTypeRef *OC) {
auto module = Dem.createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
auto node = Dem.createNode(Node::Kind::Class);
node->addChild(module, Dem);
node->addChild(Dem.createNode(Node::Kind::Identifier, OC->getName()), Dem);
return node;
}
Demangle::NodePointer
visitObjCProtocolTypeRef(const ObjCProtocolTypeRef *OC) {
auto module = Dem.createNode(Node::Kind::Module, MANGLING_MODULE_OBJC);
auto node = Dem.createNode(Node::Kind::Protocol);
node->addChild(module, Dem);
node->addChild(Dem.createNode(Node::Kind::Identifier, OC->getName()), Dem);
return node;
}
#define REF_STORAGE(Name, name, ...) \
Demangle::NodePointer visit##Name##StorageTypeRef( \
const Name##StorageTypeRef *US) { \
auto node = Dem.createNode(Node::Kind::Name); \
node->addChild(visit(US->getType()), Dem); \
return node; \
}
#include "swift/AST/ReferenceStorage.def"
Demangle::NodePointer visitSILBoxTypeRef(const SILBoxTypeRef *SB) {
auto node = Dem.createNode(Node::Kind::SILBoxType);
node->addChild(visit(SB->getBoxedType()), Dem);
return node;
}
Demangle::NodePointer visitTypeRefRequirement(const TypeRefRequirement &req) {
switch (req.getKind()) {
case RequirementKind::SameShape: {
// Not implemented.
return nullptr;
}
case RequirementKind::Conformance: {
auto r = Dem.createNode(Node::Kind::DependentGenericConformanceRequirement);
r->addChild(visit(req.getFirstType()), Dem);
r->addChild(visit(req.getSecondType()), Dem);
return r;
}
case RequirementKind::Superclass: {
auto r = Dem.createNode(Node::Kind::DependentGenericConformanceRequirement);
r->addChild(visit(req.getFirstType()), Dem);
r->addChild(visit(req.getSecondType()), Dem);
return r;
}
case RequirementKind::SameType: {
auto r = Dem.createNode(Node::Kind::DependentGenericSameTypeRequirement);
r->addChild(visit(req.getFirstType()), Dem);
r->addChild(visit(req.getSecondType()), Dem);
return r;
}
case RequirementKind::Layout:
// Not implemented.
return nullptr;
}
}
Demangle::NodePointer
visitSILBoxTypeWithLayoutTypeRef(const SILBoxTypeWithLayoutTypeRef *SB) {
auto node = Dem.createNode(Node::Kind::SILBoxTypeWithLayout);
auto layout = Dem.createNode(Node::Kind::SILBoxLayout);
for (auto &f : SB->getFields()) {
auto field =
Dem.createNode(f.isMutable() ? Node::Kind::SILBoxMutableField
: Node::Kind::SILBoxImmutableField);
field->addChild(visit(f.getType()), Dem);
layout->addChild(field, Dem);
}
node->addChild(layout, Dem);
auto signature = Dem.createNode(Node::Kind::DependentGenericSignature);
auto addCount = [&](unsigned count) {
signature->addChild(
Dem.createNode(Node::Kind::DependentGenericParamCount, count), Dem);
};
unsigned depth = 0;
unsigned index = 0;
for (auto &s : SB->getSubstitutions())
if (auto *param = dyn_cast<GenericTypeParameterTypeRef>(s.first)) {
while (param->getDepth() > depth) {
addCount(index);
++depth, index = 0;
}
assert(index == param->getIndex() && "generic params out of order");
++index;
}
for (auto &req : SB->getRequirements()) {
auto *r = visitTypeRefRequirement(req);
if (!r)
continue;
signature->addChild(r, Dem);
}
node->addChild(signature, Dem);
auto list = Dem.createNode(Node::Kind::TypeList);
for (auto &subst : SB->getSubstitutions())
list->addChild(visit(subst.second), Dem);
node->addChild(list, Dem);
return node;
}
Demangle::NodePointer visitOpaqueTypeRef(const OpaqueTypeRef *O) {
return Dem.createNode(Node::Kind::OpaqueType);
}
Demangle::NodePointer visitOpaqueArchetypeTypeRef(const OpaqueArchetypeTypeRef *O) {
auto decl = Dem.demangleType(O->getID());
if (!decl)
return nullptr;
auto index = Dem.createNode(Node::Kind::Index, O->getOrdinal());
auto argNodeLists = Dem.createNode(Node::Kind::TypeList);
for (auto argList : O->getArgumentLists()) {
auto argNodeList = Dem.createNode(Node::Kind::TypeList);
for (auto arg : argList) {
auto argNode = visit(arg);
if (!argNode)
return nullptr;
argNodeList->addChild(argNode, Dem);
}
argNodeLists->addChild(argNodeList, Dem);
}
auto node = Dem.createNode(Node::Kind::OpaqueType);
node->addChild(decl, Dem);
node->addChild(index, Dem);
node->addChild(argNodeLists, Dem);
return node;
}
};
Demangle::NodePointer TypeRef::getDemangling(Demangle::Demangler &Dem) const {
return DemanglingForTypeRef(Dem).visit(this);
}
std::optional<std::string> TypeRef::mangle(Demangle::Demangler &Dem) const {
NodePointer node = getDemangling(Dem);
if (!node)
return {};
// The mangled tree stored in this typeref implicitly assumes the type and
// global mangling, so add those back in.
auto typeMangling = Dem.createNode(Node::Kind::TypeMangling);
typeMangling->addChild(node, Dem);
auto global = Dem.createNode(Node::Kind::Global);
global->addChild(node, Dem);
auto mangling = mangleNode(global);
if (!mangling.isSuccess())
return {};
return mangling.result();
}
bool TypeRef::isConcrete() const {
GenericArgumentMap Subs;
return TypeRefIsConcrete(Subs).visit(this);
}
bool TypeRef::isConcreteAfterSubstitutions(
const GenericArgumentMap &Subs) const {
return TypeRefIsConcrete(Subs).visit(this);
}
unsigned NominalTypeTrait::getDepth() const {
if (auto P = Parent) {
switch (P->getKind()) {
case TypeRefKind::Nominal:
return 1 + cast<NominalTypeRef>(P)->getDepth();
case TypeRefKind::BoundGeneric:
return 1 + cast<BoundGenericTypeRef>(P)->getDepth();
default:
break;
}
}
return 0;
}
std::optional<GenericArgumentMap> TypeRef::getSubstMap() const {
GenericArgumentMap Substitutions;
switch (getKind()) {
case TypeRefKind::Nominal: {
auto Nom = cast<NominalTypeRef>(this);
if (auto Parent = Nom->getParent())
return Parent->getSubstMap();
return GenericArgumentMap();
}
case TypeRefKind::BoundGeneric: {
auto BG = cast<BoundGenericTypeRef>(this);
auto Depth = BG->getDepth();
unsigned Index = 0;
for (auto Param : BG->getGenericParams()) {
if (!Param->isConcrete())
return std::nullopt;
Substitutions.insert({{Depth, Index++}, Param});
}
if (auto Parent = BG->getParent()) {
auto ParentSubs = Parent->getSubstMap();
if (!ParentSubs)
return std::nullopt;
Substitutions.insert(ParentSubs->begin(), ParentSubs->end());
}
break;
}
default:
break;
}
return Substitutions;
}
bool NominalTypeTrait::isStruct() const {
return Demangle::isStruct(MangledName);
}
bool NominalTypeTrait::isEnum() const { return Demangle::isEnum(MangledName); }
bool NominalTypeTrait::isClass() const {
return Demangle::isClass(MangledName);
}
bool NominalTypeTrait::isProtocol() const {
return Demangle::isProtocol(MangledName);
}
bool NominalTypeTrait::isAlias() const {
return Demangle::isAlias(MangledName);
}
/// Visitor class to set the WasAbstract flag of any MetatypeTypeRefs
/// contained in the given type.
class ThickenMetatype
: public TypeRefVisitor<ThickenMetatype, const TypeRef *> {
TypeRefBuilder &Builder;
public:
using TypeRefVisitor<ThickenMetatype, const TypeRef *>::visit;
ThickenMetatype(TypeRefBuilder &Builder) : Builder(Builder) {}
const TypeRef *visitBuiltinTypeRef(const BuiltinTypeRef *B) {
return B;
}
const TypeRef *visitNominalTypeRef(const NominalTypeRef *N) {
return N;
}
const TypeRef *visitBoundGenericTypeRef(const BoundGenericTypeRef *BG) {
std::vector<const TypeRef *> GenericParams;
for (auto Param : BG->getGenericParams())
GenericParams.push_back(visit(Param));
auto parent = BG->getParent();
if (parent) {
parent = ThickenMetatype(Builder).visit(parent);
}
return BoundGenericTypeRef::create(Builder, BG->getMangledName(),
GenericParams, parent);
}
const TypeRef *visitTupleTypeRef(const TupleTypeRef *T) {
std::vector<const TypeRef *> Elements;
for (auto Element : T->getElements())
Elements.push_back(visit(Element));
auto Labels = T->getLabels();
return TupleTypeRef::create(Builder, Elements, Labels);
}
const TypeRef *visitFunctionTypeRef(const FunctionTypeRef *F) {
std::vector<remote::FunctionParam<const TypeRef *>> SubstitutedParams;
for (const auto &Param : F->getParameters()) {
auto typeRef = Param.getType();
SubstitutedParams.push_back(Param.withType(visit(typeRef)));
}
const TypeRef *globalActorType = nullptr;
if (F->getGlobalActor())
globalActorType = visit(F->getGlobalActor());
auto extFlags = F->getExtFlags();
const TypeRef *thrownErrorType = nullptr;
if (F->getThrownError()) {
thrownErrorType = visit(F->getThrownError());
// FIXME: fold Never and any Error to their canonical representation?
}
auto SubstitutedResult = visit(F->getResult());
return FunctionTypeRef::create(Builder, SubstitutedParams,
SubstitutedResult, F->getFlags(), extFlags,
F->getDifferentiabilityKind(),
globalActorType, thrownErrorType);
}
const TypeRef *
visitProtocolCompositionTypeRef(const ProtocolCompositionTypeRef *PC) {
return PC;
}
const TypeRef *
visitConstrainedExistentialTypeRef(const ConstrainedExistentialTypeRef *CET) {
return ConstrainedExistentialTypeRef::create(Builder, CET->getBase(),
CET->getRequirements());
}
const TypeRef *visitMetatypeTypeRef(const MetatypeTypeRef *M) {
return MetatypeTypeRef::create(Builder, visit(M->getInstanceType()),
/*WasAbstract=*/true);
}
const TypeRef *
visitExistentialMetatypeTypeRef(const ExistentialMetatypeTypeRef *EM) {
return EM;
}
const TypeRef *
visitGenericTypeParameterTypeRef(const GenericTypeParameterTypeRef *GTP) {
return GTP;
}
const TypeRef *visitDependentMemberTypeRef(const DependentMemberTypeRef *DM) {
return DM;
}
const TypeRef *visitForeignClassTypeRef(const ForeignClassTypeRef *F) {
return F;
}
const TypeRef *visitObjCClassTypeRef(const ObjCClassTypeRef *OC) {
return OC;
}
const TypeRef *visitObjCProtocolTypeRef(const ObjCProtocolTypeRef *OP) {
return OP;
}
#define REF_STORAGE(Name, name, ...) \
const TypeRef *visit##Name##StorageTypeRef(const Name##StorageTypeRef *US) { \
return US; \
}
#include "swift/AST/ReferenceStorage.def"
const TypeRef *visitSILBoxTypeRef(const SILBoxTypeRef *SB) {
return SILBoxTypeRef::create(Builder, visit(SB->getBoxedType()));
}
const TypeRef *
visitSILBoxTypeWithLayoutTypeRef(const SILBoxTypeWithLayoutTypeRef *SB) {
return SB;
}
const TypeRef *visitOpaqueTypeRef(const OpaqueTypeRef *O) {
return O;
}
const TypeRef *visitOpaqueArchetypeTypeRef(const OpaqueArchetypeTypeRef *O) {
return O;
}
};
static const TypeRef *
thickenMetatypes(TypeRefBuilder &Builder, const TypeRef *TR) {
return ThickenMetatype(Builder).visit(TR);
}
class TypeRefSubstitution
: public TypeRefVisitor<TypeRefSubstitution, const TypeRef *> {
TypeRefBuilder &Builder;
GenericArgumentMap Substitutions;
// Set true iff the Substitution map was actually used
bool DidSubstitute;
public:
using TypeRefVisitor<TypeRefSubstitution, const TypeRef *>::visit;
TypeRefSubstitution(TypeRefBuilder &Builder, GenericArgumentMap Substitutions)
: Builder(Builder), Substitutions(Substitutions), DidSubstitute(false) {}
bool didSubstitute() const { return DidSubstitute; }
const TypeRef *visitBuiltinTypeRef(const BuiltinTypeRef *B) {
return B;
}
const TypeRef *visitNominalTypeRef(const NominalTypeRef *N) {
if (N->getParent())
return NominalTypeRef::create(Builder, N->getMangledName(),
visit(N->getParent()));
return N;
}
const TypeRef *visitBoundGenericTypeRef(const BoundGenericTypeRef *BG) {
auto *Parent = BG->getParent();
if (Parent != nullptr)
Parent = visit(Parent);
std::vector<const TypeRef *> GenericParams;
for (auto Param : BG->getGenericParams())
GenericParams.push_back(visit(Param));
return BoundGenericTypeRef::create(Builder, BG->getMangledName(),
GenericParams, Parent);
}
const TypeRef *visitTupleTypeRef(const TupleTypeRef *T) {
std::vector<const TypeRef *> Elements;
for (auto Element : T->getElements())
Elements.push_back(visit(Element));
auto Labels = T->getLabels();
return TupleTypeRef::create(Builder, Elements, Labels);
}
const TypeRef *visitFunctionTypeRef(const FunctionTypeRef *F) {
std::vector<remote::FunctionParam<const TypeRef *>> SubstitutedParams;
for (const auto &Param : F->getParameters()) {
auto typeRef = Param.getType();
SubstitutedParams.push_back(Param.withType(visit(typeRef)));
}
auto SubstitutedResult = visit(F->getResult());
auto flags = F->getFlags();
auto extFlags = F->getExtFlags();
const TypeRef *globalActorType = nullptr;
if (F->getGlobalActor())
globalActorType = visit(F->getGlobalActor());
const TypeRef *thrownErrorType = nullptr;
if (F->getThrownError()) {
thrownErrorType = visit(F->getThrownError());
// FIXME: fold Never / any Error to their canonical representations?
}
return FunctionTypeRef::create(Builder, SubstitutedParams,
SubstitutedResult, flags, extFlags,
F->getDifferentiabilityKind(),
globalActorType, thrownErrorType);
}
const TypeRef *
visitProtocolCompositionTypeRef(const ProtocolCompositionTypeRef *PC) {
return PC;
}
const TypeRef *visitMetatypeTypeRef(const MetatypeTypeRef *M) {
// If the metatype's instance type does not contain any type parameters,
// substitution does not alter anything, and the empty representation
// can still be used.
if (M->isConcrete())
return M;
// When substituting a concrete type into a type parameter inside
// of a metatype's instance type, (eg; T.Type, T := C), we must
// represent the metatype at runtime as a value, even if the
// metatype naturally has an empty representation.
return MetatypeTypeRef::create(Builder, visit(M->getInstanceType()),
/*WasAbstract=*/true);
}
const TypeRef *
visitExistentialMetatypeTypeRef(const ExistentialMetatypeTypeRef *EM) {
// Existential metatypes do not contain type parameters.
assert(EM->getInstanceType()->isConcrete());
return EM;
}
std::optional<TypeRefRequirement>
visitTypeRefRequirement(const TypeRefRequirement &req) {
auto newFirst = visit(req.getFirstType());
if (!newFirst)
return std::nullopt;
switch (req.getKind()) {
case RequirementKind::SameShape:
case RequirementKind::Conformance:
case RequirementKind::Superclass:
case RequirementKind::SameType: {
auto newSecond = visit(req.getFirstType());
if (!newSecond)
return std::nullopt;
return TypeRefRequirement(req.getKind(), newFirst, newSecond);
}
case RequirementKind::Layout:
return TypeRefRequirement(req.getKind(), newFirst,
req.getLayoutConstraint());
}
llvm_unreachable("Unhandled RequirementKind in switch.");
}
const TypeRef *
visitConstrainedExistentialTypeRef(const ConstrainedExistentialTypeRef *CET) {
std::vector<TypeRefRequirement> constraints;
for (auto Req : CET->getRequirements()) {
auto substReq = visitTypeRefRequirement(Req);
if (!substReq)
continue;
constraints.emplace_back(*substReq);
}
return ConstrainedExistentialTypeRef::create(Builder, CET->getBase(),
constraints);
}
const TypeRef *
visitGenericTypeParameterTypeRef(const GenericTypeParameterTypeRef *GTP) {
auto found = Substitutions.find({GTP->getDepth(), GTP->getIndex()});
if (found == Substitutions.end())
return GTP;
assert(found->second->isConcrete());
DidSubstitute = true; // We actually used the Substitutions
// When substituting a concrete type containing a metatype into a
// type parameter, (eg: T, T := C.Type), we must also represent
// the metatype as a value.
return thickenMetatypes(Builder, found->second);
}
const TypeRef *visitDependentMemberTypeRef(const DependentMemberTypeRef *DM) {
// Substitute type parameters in the base type to get a fully concrete
// type.
auto SubstBase = visit(DM->getBase());
const TypeRef *TypeWitness = nullptr;
while (TypeWitness == nullptr) {
auto &Member = DM->getMember();
const auto &Protocol = DM->getProtocol();
// Get the original type of the witness from the conformance.
if (auto *Nominal = dyn_cast<NominalTypeRef>(SubstBase)) {
TypeWitness = Builder.lookupTypeWitness(Nominal->getMangledName(),
Member, Protocol);
} else if (auto *BG = dyn_cast<BoundGenericTypeRef>(SubstBase)) {
TypeWitness = Builder.lookupTypeWitness(BG->getMangledName(),
Member, Protocol);
}
if (TypeWitness != nullptr)
break;
// If we didn't find the member type, check the superclass.
auto *Superclass = Builder.lookupSuperclass(SubstBase);
if (Superclass == nullptr)
break;
SubstBase = Superclass;
}
auto Protocol = std::make_pair(DM->getProtocol(), false);
// We didn't find the member type, so return something to let the
// caller know we're dealing with incomplete metadata.
if (TypeWitness == nullptr)
return Builder.createDependentMemberType(DM->getMember(),
SubstBase,
Protocol);
// Likewise if we can't get the substitution map.
auto SubstMap = SubstBase->getSubstMap();
if (!SubstMap)
return Builder.createDependentMemberType(DM->getMember(),
SubstBase,
Protocol);
// Apply base type substitutions to get the fully-substituted nested type.
auto *Subst = TypeWitness->subst(Builder, *SubstMap);
// Same as above.
return thickenMetatypes(Builder, Subst);
}
const TypeRef *visitForeignClassTypeRef(const ForeignClassTypeRef *F) {
return F;
}
const TypeRef *visitObjCClassTypeRef(const ObjCClassTypeRef *OC) {
return OC;
}
const TypeRef *visitObjCProtocolTypeRef(const ObjCProtocolTypeRef *OP) {
return OP;
}
#define REF_STORAGE(Name, name, ...) \
const TypeRef *visit##Name##StorageTypeRef(const Name##StorageTypeRef *US) { \
return Name##StorageTypeRef::create(Builder, visit(US->getType())); \
}
#include "swift/AST/ReferenceStorage.def"
const TypeRef *visitSILBoxTypeRef(const SILBoxTypeRef *SB) {
return SILBoxTypeRef::create(Builder, visit(SB->getBoxedType()));
}
const TypeRef *
visitSILBoxTypeWithLayoutTypeRef(const SILBoxTypeWithLayoutTypeRef *SB) {
return SB;
}
const TypeRef *visitOpaqueTypeRef(const OpaqueTypeRef *O) { return O; }
const TypeRef *visitOpaqueArchetypeTypeRef(const OpaqueArchetypeTypeRef *O) {
std::vector<const TypeRef *> newArgsBuffer;
for (auto argList : O->getArgumentLists()) {
for (auto arg : argList) {
newArgsBuffer.push_back(visit(arg));
}
}
std::vector<llvm::ArrayRef<const TypeRef *>> newArgLists;
return OpaqueArchetypeTypeRef::create(Builder, O->getID(), O->getDescription(),
O->getOrdinal(),
newArgLists);
}
};
const TypeRef *TypeRef::subst(TypeRefBuilder &Builder,
const GenericArgumentMap &Subs) const {
return TypeRefSubstitution(Builder, Subs).visit(this);
}
const TypeRef *TypeRef::subst(TypeRefBuilder &Builder,
const GenericArgumentMap &Subs,
bool &DidSubstitute) const {
auto subst = TypeRefSubstitution(Builder, Subs);
auto TR = subst.visit(this);
DidSubstitute = subst.didSubstitute();
return TR;
}
bool TypeRef::deriveSubstitutions(GenericArgumentMap &Subs,
const TypeRef *OrigTR,
const TypeRef *SubstTR) {
// Walk into parent types of concrete nominal types.
if (auto *O = dyn_cast<NominalTypeRef>(OrigTR)) {
if (auto *S = dyn_cast<NominalTypeRef>(SubstTR)) {
if (!!O->getParent() != !!S->getParent() ||
O->getMangledName() != S->getMangledName())
return false;
if (O->getParent() &&
!deriveSubstitutions(Subs,
O->getParent(),
S->getParent()))
return false;
return true;
}
}
// Decompose arguments of bound generic types in parallel.
if (auto *O = dyn_cast<BoundGenericTypeRef>(OrigTR)) {
if (auto *S = dyn_cast<BoundGenericTypeRef>(SubstTR)) {
if (!!O->getParent() != !!S->getParent() ||
O->getMangledName() != S->getMangledName() ||
O->getGenericParams().size() != S->getGenericParams().size())
return false;
if (O->getParent() &&
!deriveSubstitutions(Subs,
O->getParent(),
S->getParent()))
return false;
for (unsigned i = 0, e = O->getGenericParams().size(); i < e; ++i) {
if (!deriveSubstitutions(Subs,
O->getGenericParams()[i],
S->getGenericParams()[i]))
return false;
}
return true;
}
}
// Decompose tuple element types in parallel.
if (auto *O = dyn_cast<TupleTypeRef>(OrigTR)) {
if (auto *S = dyn_cast<TupleTypeRef>(SubstTR)) {
if (O->getElements().size() != S->getElements().size())
return false;
for (unsigned i = 0, e = O->getElements().size(); i < e; ++i) {
if (!deriveSubstitutions(Subs,
O->getElements()[i],
S->getElements()[i]))
return false;
}
return true;
}
}
// Decompose parameter and result types in parallel.
if (auto *O = dyn_cast<FunctionTypeRef>(OrigTR)) {
if (auto *S = dyn_cast<FunctionTypeRef>(SubstTR)) {
auto oParams = O->getParameters();
auto sParams = S->getParameters();
if (oParams.size() != sParams.size())
return false;
for (auto index : indices(oParams)) {
if (!deriveSubstitutions(Subs, oParams[index].getType(),
sParams[index].getType()))
return false;
}
if (!deriveSubstitutions(Subs,
O->getResult(),
S->getResult()))
return false;
return true;
}
}
// Walk down into the instance type.
if (auto *O = dyn_cast<MetatypeTypeRef>(OrigTR)) {
if (auto *S = dyn_cast<MetatypeTypeRef>(SubstTR)) {
if (!deriveSubstitutions(Subs,
O->getInstanceType(),
S->getInstanceType()))
return false;
return true;
}
}
// Walk down into the referent storage type.
if (auto *O = dyn_cast<ReferenceStorageTypeRef>(OrigTR)) {
if (auto *S = dyn_cast<ReferenceStorageTypeRef>(SubstTR)) {
if (O->getKind() != S->getKind())
return false;
if (!deriveSubstitutions(Subs,
O->getType(),
S->getType()))
return false;
return true;
}
}
if (isa<DependentMemberTypeRef>(OrigTR)) {
// FIXME: Do some validation here?
return true;
}
// If the original type is a generic type parameter, just make
// sure the substituted type matches anything we've already
// seen.
if (auto *O = dyn_cast<GenericTypeParameterTypeRef>(OrigTR)) {
DepthAndIndex key = {O->getDepth(), O->getIndex()};
auto found = Subs.find(key);
if (found == Subs.end()) {
Subs[key] = SubstTR;
return true;
}
return (found->second == SubstTR);
}
// Anything else must be concrete and the two types must match
// exactly.
return (OrigTR == SubstTR);
}
#endif
|