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
|
//===--- TypeCheckMacros.cpp - Macro Handling ----------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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
//
//===----------------------------------------------------------------------===//
//
// This file implements support for the evaluation of macros.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckMacros.h"
#include "../AST/InlinableText.h"
#include "TypeCheckType.h"
#include "TypeChecker.h"
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/ASTBridging.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTMangler.h"
#include "swift/AST/ASTNode.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/Expr.h"
#include "swift/AST/FreestandingMacroExpansion.h"
#include "swift/AST/MacroDefinition.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/PluginLoader.h"
#include "swift/AST/PluginRegistry.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/BasicBridging.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Lazy.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Bridging/ASTGen.h"
#include "swift/Demangling/Demangler.h"
#include "swift/Demangling/ManglingMacros.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Subsystems.h"
#include "llvm/Config/config.h"
using namespace swift;
#if SWIFT_BUILD_SWIFT_SYNTAX
/// Look for macro's type metadata given its external module and type name.
static void const *
lookupMacroTypeMetadataByExternalName(ASTContext &ctx, StringRef moduleName,
StringRef typeName,
LoadedLibraryPlugin *plugin) {
// Look up the type metadata accessor as a struct, enum, or class.
const Demangle::Node::Kind typeKinds[] = {
Demangle::Node::Kind::Structure,
Demangle::Node::Kind::Enum,
Demangle::Node::Kind::Class
};
void *accessorAddr = nullptr;
for (auto typeKind : typeKinds) {
auto symbolName = Demangle::mangledNameForTypeMetadataAccessor(
moduleName, typeName, typeKind);
accessorAddr = plugin->getAddressOfSymbol(symbolName.c_str());
if (accessorAddr)
break;
}
if (!accessorAddr)
return nullptr;
// Call the accessor to form type metadata.
using MetadataAccessFunc = const void *(MetadataRequest);
auto accessor = reinterpret_cast<MetadataAccessFunc*>(accessorAddr);
return accessor(MetadataRequest(MetadataState::Complete));
}
#endif
/// Translate an argument provided as a string literal into an identifier,
/// or return \c None and emit an error if it cannot be done.
std::optional<Identifier> getIdentifierFromStringLiteralArgument(
ASTContext &ctx, MacroExpansionExpr *expansion, unsigned index) {
auto argList = expansion->getArgs();
// If there's no argument here, an error was diagnosed elsewhere.
if (!argList || index >= argList->size()) {
return std::nullopt;
}
auto arg = argList->getExpr(index);
auto stringLiteral = dyn_cast<StringLiteralExpr>(arg);
if (!stringLiteral) {
ctx.Diags.diagnose(
arg->getLoc(), diag::external_macro_arg_not_type_name, index
);
return std::nullopt;
}
auto contents = stringLiteral->getValue();
if (!Lexer::isIdentifier(contents)) {
ctx.Diags.diagnose(
arg->getLoc(), diag::external_macro_arg_not_type_name, index
);
return std::nullopt;
}
return ctx.getIdentifier(contents);
}
/// For a macro expansion expression that is known to be #externalMacro,
/// handle the definition.
#if SWIFT_BUILD_SWIFT_SYNTAX
static MacroDefinition handleExternalMacroDefinition(
ASTContext &ctx, MacroExpansionExpr *expansion) {
// Dig out the module and type name.
auto moduleName = getIdentifierFromStringLiteralArgument(ctx, expansion, 0);
if (!moduleName) {
return MacroDefinition::forInvalid();
}
auto typeName = getIdentifierFromStringLiteralArgument(ctx, expansion, 1);
if (!typeName) {
return MacroDefinition::forInvalid();
}
return MacroDefinition::forExternal(*moduleName, *typeName);
}
#endif // SWIFT_BUILD_SWIFT_SYNTAX
MacroDefinition MacroDefinitionRequest::evaluate(
Evaluator &evaluator, MacroDecl *macro
) const {
// If no definition was provided, the macro is... undefined, of course.
auto definition = macro->definition;
if (!definition)
return MacroDefinition::forUndefined();
#if SWIFT_BUILD_SWIFT_SYNTAX
ASTContext &ctx = macro->getASTContext();
auto sourceFile = macro->getParentSourceFile();
BridgedStringRef externalMacroName{nullptr, 0};
ptrdiff_t *replacements = nullptr;
ptrdiff_t numReplacements = 0;
ptrdiff_t *genericReplacements = nullptr;
ptrdiff_t numGenericReplacements = 0;
// Parse 'macro' decl in swift_ASTGen_checkMacroDefinition.
// NOTE: We don't use source->getExportedSourceFile() because it parses the
// entire source buffer, which we don't want. Usually 'macro' decl is not in
// the same file as the expansion, so we only want to parse only the decl.
// FIXME: When we migrate to SwiftParser, use the parsed syntax tree.
auto &SM = ctx.SourceMgr;
StringRef sourceFileText =
SM.getEntireTextForBuffer(*sourceFile->getBufferID());
StringRef macroDeclText =
SM.extractText(Lexer::getCharSourceRangeFromSourceRange(
SM, macro->getSourceRangeIncludingAttrs()));
auto checkResult = swift_ASTGen_checkMacroDefinition(
&ctx.Diags, sourceFileText, macroDeclText, &externalMacroName,
&replacements, &numReplacements, &genericReplacements,
&numGenericReplacements);
// Clean up after the call.
SWIFT_DEFER {
swift_ASTGen_freeBridgedString(externalMacroName);
swift_ASTGen_freeExpansionReplacements(replacements, numReplacements);
// swift_ASTGen_freeExpansionGenericReplacements(genericReplacements, numGenericReplacements); // FIXME: !!!!!!
};
if (checkResult < 0 && ctx.CompletionCallback) {
// If the macro failed to check and we are in code completion mode, pretend
// it's an arbitrary macro. This allows us to get call argument completions
// inside `#externalMacro`.
checkResult = BridgedMacroDefinitionKind::BridgedExpandedMacro;
}
if (checkResult < 0)
return MacroDefinition::forInvalid();
switch (static_cast<BridgedMacroDefinitionKind>(checkResult)) {
case BridgedExpandedMacro:
// Handle expanded macros below.
break;
case BridgedExternalMacro: {
// An external macro described as ModuleName.TypeName. Get both identifiers.
assert(!replacements && "External macro doesn't have replacements");
assert(!genericReplacements && "External macro doesn't have genericReplacements");
StringRef externalMacroStr = externalMacroName.unbridged();
StringRef externalModuleName, externalTypeName;
std::tie(externalModuleName, externalTypeName) = externalMacroStr.split('.');
Identifier moduleName = ctx.getIdentifier(externalModuleName);
Identifier typeName = ctx.getIdentifier(externalTypeName);
return MacroDefinition::forExternal(moduleName, typeName);
}
case BridgedBuiltinExternalMacro:
return MacroDefinition::forBuiltin(BuiltinMacroKind::ExternalMacro);
case BridgedBuiltinIsolationMacro:
return MacroDefinition::forBuiltin(BuiltinMacroKind::IsolationMacro);
}
// Type-check the macro expansion.
Type resultType = macro->mapTypeIntoContext(macro->getResultInterfaceType());
constraints::ContextualTypeInfo contextualType {
TypeLoc::withoutLoc(resultType),
// FIXME: Add a contextual type purpose for macro definition checking.
ContextualTypePurpose::CTP_CoerceOperand
};
PrettyStackTraceDecl debugStack("type checking macro definition", macro);
Type typeCheckedType = TypeChecker::typeCheckExpression(
definition, macro, contextualType,
TypeCheckExprFlags::DisableMacroExpansions);
if (!typeCheckedType)
return MacroDefinition::forInvalid();
// Dig out the macro that was expanded.
auto expansion = cast<MacroExpansionExpr>(definition);
auto expandedMacro =
dyn_cast_or_null<MacroDecl>(expansion->getMacroRef().getDecl());
if (!expandedMacro)
return MacroDefinition::forInvalid();
// Handle external macros after type-checking.
auto builtinKind = expandedMacro->getBuiltinKind();
if (builtinKind == BuiltinMacroKind::ExternalMacro)
return handleExternalMacroDefinition(ctx, expansion);
// Expansion string text.
StringRef expansionText = externalMacroName.unbridged();
// Copy over the replacements.
SmallVector<ExpandedMacroReplacement, 2> replacementsVec;
for (unsigned i: range(0, numReplacements)) {
replacementsVec.push_back(
{ static_cast<unsigned>(replacements[3*i]),
static_cast<unsigned>(replacements[3*i+1]),
static_cast<unsigned>(replacements[3*i+2])});
}
// Copy over the genericReplacements.
SmallVector<ExpandedMacroReplacement, 2> genericReplacementsVec;
for (unsigned i: range(0, numGenericReplacements)) {
genericReplacementsVec.push_back(
{ static_cast<unsigned>(genericReplacements[3*i]),
static_cast<unsigned>(genericReplacements[3*i+1]),
static_cast<unsigned>(genericReplacements[3*i+2])});
}
return MacroDefinition::forExpanded(ctx, expansionText, replacementsVec, genericReplacementsVec);
#else
macro->diagnose(diag::macro_unsupported);
return MacroDefinition::forInvalid();
#endif
}
static llvm::Expected<LoadedExecutablePlugin *>
initializeExecutablePlugin(ASTContext &ctx,
LoadedExecutablePlugin *executablePlugin,
StringRef libraryPath, Identifier moduleName) {
// Lock the plugin while initializing.
// Note that'executablePlugn' can be shared between multiple ASTContext.
executablePlugin->lock();
SWIFT_DEFER { executablePlugin->unlock(); };
// FIXME: Ideally this should be done right after invoking the plugin.
// But plugin loading is in libAST and it can't link ASTGen symbols.
if (!executablePlugin->isInitialized()) {
#if SWIFT_BUILD_SWIFT_SYNTAX
if (!swift_ASTGen_initializePlugin(executablePlugin, &ctx.Diags)) {
return llvm::createStringError(
llvm::inconvertibleErrorCode(), "'%s' produced malformed response",
executablePlugin->getExecutablePath().data());
}
// Resend the compiler capability on reconnect.
auto *callback = new std::function<void(void)>(
[executablePlugin]() {
(void)swift_ASTGen_initializePlugin(
executablePlugin, /*diags=*/nullptr);
});
executablePlugin->addOnReconnect(callback);
executablePlugin->setCleanup([executablePlugin] {
swift_ASTGen_deinitializePlugin(executablePlugin);
});
#endif
}
// If this is a plugin server, load the library.
if (!libraryPath.empty()) {
#if SWIFT_BUILD_SWIFT_SYNTAX
llvm::SmallString<128> resolvedLibraryPath;
auto fs = ctx.ClangImporterOpts.HasClangIncludeTreeRoot
? llvm::vfs::getRealFileSystem()
: ctx.SourceMgr.getFileSystem();
if (auto err = fs->getRealPath(libraryPath, resolvedLibraryPath)) {
return llvm::createStringError(err, err.message());
}
std::string resolvedLibraryPathStr(resolvedLibraryPath);
std::string moduleNameStr(moduleName.str());
BridgedStringRef bridgedErrorOut{nullptr, 0};
bool loaded = swift_ASTGen_pluginServerLoadLibraryPlugin(
executablePlugin, resolvedLibraryPathStr.c_str(), moduleNameStr.c_str(),
&bridgedErrorOut);
auto errorOut = bridgedErrorOut.unbridged();
if (!loaded) {
SWIFT_DEFER { swift_ASTGen_freeBridgedString(errorOut); };
return llvm::createStringError(
llvm::inconvertibleErrorCode(),
"failed to load library plugin '%s' in plugin server '%s'; %s",
resolvedLibraryPathStr.c_str(),
executablePlugin->getExecutablePath().data(), errorOut.data());
}
assert(errorOut.data() == nullptr);
// Set a callback to load the library again on reconnections.
auto *callback = new std::function<void(void)>(
[executablePlugin, resolvedLibraryPathStr, moduleNameStr]() {
(void)swift_ASTGen_pluginServerLoadLibraryPlugin(
executablePlugin, resolvedLibraryPathStr.c_str(),
moduleNameStr.c_str(),
/*errorOut=*/nullptr);
});
executablePlugin->addOnReconnect(callback);
// Remove the callback and deallocate it when this ASTContext is destructed.
ctx.addCleanup([executablePlugin, callback]() {
executablePlugin->removeOnReconnect(callback);
delete callback;
});
#endif
}
return executablePlugin;
}
CompilerPluginLoadResult
CompilerPluginLoadRequest::evaluate(Evaluator &evaluator, ASTContext *ctx,
Identifier moduleName) const {
PluginLoader &loader = ctx->getPluginLoader();
const auto &entry = loader.lookupPluginByModuleName(moduleName);
SmallString<0> errorMessage;
if (!entry.executablePath.empty()) {
llvm::Expected<LoadedExecutablePlugin *> executablePlugin =
loader.loadExecutablePlugin(entry.executablePath);
if (executablePlugin) {
if (ctx->LangOpts.EnableMacroLoadingRemarks) {
unsigned tag = entry.libraryPath.empty() ? 1 : 2;
ctx->Diags.diagnose(SourceLoc(), diag::macro_loaded, moduleName, tag,
entry.executablePath, entry.libraryPath);
}
executablePlugin = initializeExecutablePlugin(
*ctx, executablePlugin.get(), entry.libraryPath, moduleName);
}
if (executablePlugin)
return executablePlugin.get();
llvm::handleAllErrors(executablePlugin.takeError(),
[&](const llvm::ErrorInfoBase &err) {
if (!errorMessage.empty())
errorMessage += ", ";
errorMessage += err.message();
});
} else if (!entry.libraryPath.empty()) {
llvm::Expected<LoadedLibraryPlugin *> libraryPlugin =
loader.loadLibraryPlugin(entry.libraryPath);
if (libraryPlugin) {
if (ctx->LangOpts.EnableMacroLoadingRemarks) {
ctx->Diags.diagnose(SourceLoc(), diag::macro_loaded, moduleName, 0,
entry.libraryPath, StringRef());
}
return libraryPlugin.get();
} else {
llvm::handleAllErrors(libraryPlugin.takeError(),
[&](const llvm::ErrorInfoBase &err) {
if (!errorMessage.empty())
errorMessage += ", ";
errorMessage += err.message();
});
}
}
if (!errorMessage.empty()) {
NullTerminatedStringRef err(errorMessage, *ctx);
return CompilerPluginLoadResult::error(err);
} else {
NullTerminatedStringRef errMsg(
"plugin for module '" + moduleName.str() + "' not found", *ctx);
return CompilerPluginLoadResult::error(errMsg);
}
}
static ExternalMacroDefinition
resolveInProcessMacro(ASTContext &ctx, Identifier moduleName,
Identifier typeName, LoadedLibraryPlugin *plugin) {
#if SWIFT_BUILD_SWIFT_SYNTAX
/// Look for the type metadata given the external module and type names.
auto macroMetatype = lookupMacroTypeMetadataByExternalName(
ctx, moduleName.str(), typeName.str(), plugin);
if (macroMetatype) {
// Check whether the macro metatype is in-process.
if (auto inProcess = swift_ASTGen_resolveMacroType(macroMetatype)) {
// Make sure we clean up after the macro.
ctx.addCleanup([inProcess]() {
swift_ASTGen_destroyMacro(inProcess);
});
return ExternalMacroDefinition{
ExternalMacroDefinition::PluginKind::InProcess, inProcess};
} else {
NullTerminatedStringRef err(
"'" + moduleName.str() + "." + typeName.str() +
"' is not a valid macro implementation type in library plugin '" +
StringRef(plugin->getLibraryPath()) + "'",
ctx);
return ExternalMacroDefinition::error(err);
}
}
NullTerminatedStringRef err("'" + moduleName.str() + "." + typeName.str() +
"' could not be found in library plugin '" +
StringRef(plugin->getLibraryPath()) + "'",
ctx);
return ExternalMacroDefinition::error(err);
#endif
return ExternalMacroDefinition::error(
"the current compiler was not built with macro support");
}
static ExternalMacroDefinition
resolveExecutableMacro(ASTContext &ctx,
LoadedExecutablePlugin *executablePlugin,
Identifier moduleName, Identifier typeName) {
#if SWIFT_BUILD_SWIFT_SYNTAX
if (auto *execMacro = swift_ASTGen_resolveExecutableMacro(
moduleName.get(), typeName.get(), executablePlugin)) {
// Make sure we clean up after the macro.
ctx.addCleanup(
[execMacro]() { swift_ASTGen_destroyExecutableMacro(execMacro); });
return ExternalMacroDefinition{
ExternalMacroDefinition::PluginKind::Executable, execMacro};
}
// NOTE: this is not reachable because executable macro resolution always
// succeeds.
NullTerminatedStringRef err(
"'" + moduleName.str() + "." + typeName.str() +
"' could not be found in executable plugin" +
StringRef(executablePlugin->getExecutablePath()),
ctx);
return ExternalMacroDefinition::error(err);
#endif
return ExternalMacroDefinition::error(
"the current compiler was not built with macro support");
}
ExternalMacroDefinition
ExternalMacroDefinitionRequest::evaluate(Evaluator &evaluator, ASTContext *ctx,
Identifier moduleName,
Identifier typeName) const {
// Try to load a plugin module from the plugin search paths. If it
// succeeds, resolve in-process from that plugin
CompilerPluginLoadRequest loadRequest{ctx, moduleName};
CompilerPluginLoadResult loaded = evaluateOrDefault(
evaluator, loadRequest, CompilerPluginLoadResult::error("request error"));
if (auto loadedLibrary = loaded.getAsLibraryPlugin()) {
return resolveInProcessMacro(*ctx, moduleName, typeName, loadedLibrary);
}
if (auto *executablePlugin = loaded.getAsExecutablePlugin()) {
return resolveExecutableMacro(*ctx, executablePlugin, moduleName, typeName);
}
return ExternalMacroDefinition::error(loaded.getErrorMessage());
}
/// Adjust the given mangled name for a macro expansion to produce a valid
/// buffer name.
static std::string adjustMacroExpansionBufferName(StringRef name) {
if (name.empty()) {
return "<macro-expansion>";
}
std::string result;
if (name.starts_with(MANGLING_PREFIX_STR)) {
result += MACRO_EXPANSION_BUFFER_MANGLING_PREFIX;
name = name.drop_front(StringRef(MANGLING_PREFIX_STR).size());
}
result += name;
result += ".swift";
return result;
}
std::optional<unsigned>
ExpandMacroExpansionExprRequest::evaluate(Evaluator &evaluator,
MacroExpansionExpr *mee) const {
ConcreteDeclRef macroRef = mee->getMacroRef();
assert(macroRef && isa<MacroDecl>(macroRef.getDecl()) &&
"MacroRef should be set before expansion");
auto *macro = cast<MacroDecl>(macroRef.getDecl());
if (macro->getMacroRoles().contains(MacroRole::Expression)) {
return expandMacroExpr(mee);
}
// For a non-expression macro, expand it as a declaration.
else if (macro->getMacroRoles().contains(MacroRole::Declaration) ||
macro->getMacroRoles().contains(MacroRole::CodeItem)) {
if (!mee->getSubstituteDecl()) {
(void)mee->createSubstituteDecl();
}
// Return the expanded buffer ID.
return evaluateOrDefault(
evaluator, ExpandMacroExpansionDeclRequest(mee->getSubstituteDecl()),
std::nullopt);
}
// Other macro roles may also be encountered here, as they use
// `MacroExpansionExpr` for resolution. In those cases, do not expand.
return std::nullopt;
}
ArrayRef<unsigned> ExpandMemberAttributeMacros::evaluate(Evaluator &evaluator,
Decl *decl) const {
if (decl->isImplicit())
return { };
// Member attribute macros do not apply to accessors.
if (isa<AccessorDecl>(decl))
return { };
// Member attribute macros do not apply to macro-expanded members.
if (decl->isInMacroExpansionInContext())
return { };
auto *parentDecl = decl->getDeclContext()->getAsDecl();
if (!parentDecl || !isa<IterableDeclContext>(parentDecl))
return { };
if (isa<PatternBindingDecl>(decl))
return { };
SmallVector<unsigned, 2> bufferIDs;
parentDecl->forEachAttachedMacro(MacroRole::MemberAttribute,
[&](CustomAttr *attr, MacroDecl *macro) {
if (auto bufferID = expandAttributes(attr, macro, decl))
bufferIDs.push_back(*bufferID);
});
return parentDecl->getASTContext().AllocateCopy(bufferIDs);
}
ArrayRef<unsigned> ExpandSynthesizedMemberMacroRequest::evaluate(
Evaluator &evaluator, Decl *decl
) const {
SmallVector<unsigned, 2> bufferIDs;
decl->forEachAttachedMacro(MacroRole::Member,
[&](CustomAttr *attr, MacroDecl *macro) {
if (auto bufferID = expandMembers(attr, macro, decl))
bufferIDs.push_back(*bufferID);
});
return decl->getASTContext().AllocateCopy(bufferIDs);
}
ArrayRef<unsigned>
ExpandPeerMacroRequest::evaluate(Evaluator &evaluator, Decl *decl) const {
SmallVector<unsigned, 2> bufferIDs;
decl->forEachAttachedMacro(MacroRole::Peer,
[&](CustomAttr *attr, MacroDecl *macro) {
if (auto bufferID = expandPeers(attr, macro, decl))
bufferIDs.push_back(*bufferID);
});
return decl->getASTContext().AllocateCopy(bufferIDs);
}
static Identifier makeIdentifier(ASTContext &ctx, StringRef name) {
return ctx.getIdentifier(name);
}
static Identifier makeIdentifier(ASTContext &ctx, std::nullptr_t) {
return Identifier();
}
bool swift::isInvalidAttachedMacro(MacroRole role,
Decl *attachedTo) {
switch (role) {
#define FREESTANDING_MACRO_ROLE(Name, Description) case MacroRole::Name:
#define ATTACHED_MACRO_ROLE(Name, Description, MangledChar)
#include "swift/Basic/MacroRoles.def"
llvm_unreachable("Invalid macro role for attached macro");
case MacroRole::Accessor:
// Only var decls and subscripts have accessors.
if (isa<AbstractStorageDecl>(attachedTo) && !isa<ParamDecl>(attachedTo))
return false;
break;
case MacroRole::MemberAttribute:
case MacroRole::Member:
// Nominal types and extensions can have members.
if (isa<NominalTypeDecl>(attachedTo) || isa<ExtensionDecl>(attachedTo))
return false;
break;
case MacroRole::Peer:
// Peer macros are allowed on everything except parameters.
if (!isa<ParamDecl>(attachedTo))
return false;
break;
case MacroRole::Conformance:
case MacroRole::Extension:
// Only primary declarations of nominal types
if (isa<NominalTypeDecl>(attachedTo))
return false;
break;
case MacroRole::Preamble:
case MacroRole::Body:
// Only function declarations.
if (isa<AbstractFunctionDecl>(attachedTo))
return false;
break;
}
return true;
}
static void diagnoseInvalidDecl(Decl *decl,
MacroDecl *macro,
llvm::function_ref<bool(DeclName)> coversName) {
auto &ctx = decl->getASTContext();
// Diagnose invalid declaration kinds.
if (isa<ImportDecl>(decl) ||
isa<OperatorDecl>(decl) ||
isa<PrecedenceGroupDecl>(decl) ||
isa<MacroDecl>(decl) ||
isa<ExtensionDecl>(decl)) {
decl->diagnose(diag::invalid_decl_in_macro_expansion,
decl->getDescriptiveKind());
decl->setInvalid();
if (auto *extension = dyn_cast<ExtensionDecl>(decl)) {
extension->setExtendedNominal(nullptr);
}
return;
}
// Diagnose `@main` types.
if (auto *mainAttr = decl->getAttrs().getAttribute<MainTypeAttr>()) {
ctx.Diags.diagnose(mainAttr->getLocation(),
diag::invalid_main_type_in_macro_expansion);
mainAttr->setInvalid();
}
// Diagnose default literal type overrides.
if (auto *typeAlias = dyn_cast<TypeAliasDecl>(decl)) {
auto name = typeAlias->getBaseIdentifier();
#define EXPRESSIBLE_BY_LITERAL_PROTOCOL_WITH_NAME(_, __, typeName, \
supportsOverride) \
if (supportsOverride && name == makeIdentifier(ctx, typeName)) { \
typeAlias->diagnose(diag::literal_type_in_macro_expansion, \
makeIdentifier(ctx, typeName)); \
typeAlias->setInvalid(); \
return; \
}
#include "swift/AST/KnownProtocols.def"
#undef EXPRESSIBLE_BY_LITERAL_PROTOCOL_WITH_NAME
}
// Diagnose value decls with names not covered by the macro
if (auto *value = dyn_cast<ValueDecl>(decl)) {
auto name = value->getName();
// Unique names are always permitted.
if (MacroDecl::isUniqueMacroName(name.getBaseName().userFacingName()))
return;
if (coversName(name)) {
return;
}
value->diagnose(diag::invalid_macro_introduced_name,
name, macro->getBaseName());
}
}
/// Diagnose macro expansions that produce any of the following declarations:
/// - Import declarations
/// - Operator and precedence group declarations
/// - Macro declarations
/// - Extensions
/// - Types with `@main` attributes
/// - Top-level default literal type overrides
/// - Value decls with names not covered by the macro declaration.
static void validateMacroExpansion(SourceFile *expansionBuffer,
MacroDecl *macro,
ValueDecl *attachedTo,
MacroRole role) {
// Gather macro-introduced names
llvm::SmallVector<DeclName, 2> introducedNames;
macro->getIntroducedNames(role, attachedTo, introducedNames);
llvm::SmallDenseSet<DeclName, 2> introducedNameSet(
introducedNames.begin(), introducedNames.end());
auto coversName = [&](DeclName name) -> bool {
return (introducedNameSet.count(name) ||
introducedNameSet.count(name.getBaseName()) ||
introducedNameSet.count(MacroDecl::getArbitraryName()));
};
for (auto item : expansionBuffer->getTopLevelItems()) {
auto &ctx = expansionBuffer->getASTContext();
auto *decl = item.dyn_cast<Decl *>();
if (!decl) {
if (role != MacroRole::CodeItem &&
role != MacroRole::Preamble &&
role != MacroRole::Body) {
ctx.Diags.diagnose(item.getStartLoc(),
diag::expected_macro_expansion_decls);
}
continue;
}
// Certain macro roles can generate special declarations.
if (isa<AccessorDecl>(decl) && role == MacroRole::Accessor) {
auto *var = dyn_cast<VarDecl>(attachedTo);
if (var && var->isLet()) {
ctx.Diags.diagnose(var->getLoc(),
diag::let_accessor_expansion)
.warnUntilSwiftVersion(6);
}
continue;
}
if (isa<ExtensionDecl>(decl) && role == MacroRole::Conformance) {
continue;
}
if (role == MacroRole::Extension) {
auto *extension = dyn_cast<ExtensionDecl>(decl);
for (auto *member : extension->getMembers()) {
diagnoseInvalidDecl(member, macro, coversName);
}
continue;
}
diagnoseInvalidDecl(decl, macro, coversName);
}
}
/// Determine whether the given source file is from an expansion of the given
/// macro.
static bool isFromExpansionOfMacro(SourceFile *sourceFile, MacroDecl *macro,
MacroRole role) {
while (sourceFile) {
auto expansion = sourceFile->getMacroExpansion();
if (!expansion)
return false;
if (auto expansionExpr = dyn_cast_or_null<MacroExpansionExpr>(
expansion.dyn_cast<Expr *>())) {
if (expansionExpr->getMacroRef().getDecl() == macro)
return true;
} else if (auto expansionDecl = dyn_cast_or_null<MacroExpansionDecl>(
expansion.dyn_cast<Decl *>())) {
if (expansionDecl->getMacroRef().getDecl() == macro)
return true;
} else if (auto *macroAttr = sourceFile->getAttachedMacroAttribute()) {
auto *decl = expansion.dyn_cast<Decl *>();
auto *macroDecl = decl->getResolvedMacro(macroAttr);
if (!macroDecl)
return false;
return macroDecl == macro &&
sourceFile->getFulfilledMacroRole() == role;
} else {
llvm_unreachable("Unknown macro expansion node kind");
}
sourceFile = sourceFile->getEnclosingSourceFile();
}
return false;
}
/// Expand a macro definition.
static std::string expandMacroDefinition(
ExpandedMacroDefinition def, MacroDecl *macro,
SubstitutionMap subs,
ArgumentList *args) {
ASTContext &ctx = macro->getASTContext();
std::string expandedResult;
StringRef originalText = def.getExpansionText();
unsigned startIdx = 0;
unsigned replacementsIdx = 0;
unsigned genericReplacementsIdx = 0;
auto totalReplacementsCount =
def.getReplacements().size() + def.getGenericReplacements().size();
while (replacementsIdx + genericReplacementsIdx < totalReplacementsCount) {
ExpandedMacroReplacement replacement;
bool isExpressionReplacement = true;
// Pick the "next" replacement, in order as they appear in the source text
auto canPickExpressionReplacement = replacementsIdx < def.getReplacements().size();
auto canPickGenericReplacement = genericReplacementsIdx < def.getGenericReplacements().size();
if (canPickExpressionReplacement && canPickGenericReplacement) {
auto expressionReplacement = def.getReplacements()[replacementsIdx];
auto genericReplacement =
def.getGenericReplacements()[genericReplacementsIdx];
isExpressionReplacement =
expressionReplacement.startOffset < genericReplacement.startOffset;
replacement =
isExpressionReplacement ? expressionReplacement : genericReplacement;
} else if (canPickExpressionReplacement) {
isExpressionReplacement = true;
replacement = def.getReplacements()[replacementsIdx];
} else if (canPickGenericReplacement) {
isExpressionReplacement = false;
replacement = def.getGenericReplacements()[replacementsIdx];
} else {
assert(false && "should always select a requirement explicitly rather "
"than fall through");
}
replacementsIdx += isExpressionReplacement ? 1 : 0;
genericReplacementsIdx += isExpressionReplacement ? 0 : 1;
// Add the original text up to the first replacement.
expandedResult.append(originalText.begin() + startIdx,
originalText.begin() + replacement.startOffset);
// Add the replacement text.
if (isExpressionReplacement) {
auto argExpr = args->getArgExprs()[replacement.parameterIndex];
SmallString<32> argTextBuffer;
auto argText =
extractInlinableText(ctx.SourceMgr, argExpr, argTextBuffer);
expandedResult.append(argText);
} else {
auto typeArgType = subs.getReplacementTypes()[replacement.parameterIndex];
std::string typeNameString;
llvm::raw_string_ostream os(typeNameString);
typeArgType.print(os);
expandedResult.append(typeNameString);
}
// Update the starting position.
startIdx = replacement.endOffset;
}
// Add the remaining text.
expandedResult.append(
originalText.begin() + startIdx,
originalText.end());
return expandedResult;
}
static GeneratedSourceInfo::Kind getGeneratedSourceInfoKind(MacroRole role) {
switch (role) {
#define MACRO_ROLE(Name, Description) \
case MacroRole::Name: \
return GeneratedSourceInfo::Name##MacroExpansion;
#include "swift/Basic/MacroRoles.def"
}
}
// If this storage declaration is a variable with an explicit initializer,
// return the range from the `=` to the end of the explicit initializer.
static std::optional<SourceRange>
getExplicitInitializerRange(AbstractStorageDecl *storage) {
auto var = dyn_cast<VarDecl>(storage);
if (!var)
return std::nullopt;
auto pattern = var->getParentPatternBinding();
if (!pattern)
return std::nullopt;
unsigned index = pattern->getPatternEntryIndexForVarDecl(var);
SourceLoc equalLoc = pattern->getEqualLoc(index);
SourceRange initRange = pattern->getOriginalInitRange(index);
if (equalLoc.isInvalid() || initRange.End.isInvalid())
return std::nullopt;
return SourceRange(equalLoc, initRange.End);
}
/// Compute the original source range for expanding a preamble macro.
static CharSourceRange getPreambleMacroOriginalRange(AbstractFunctionDecl *fn) {
ASTContext &ctx = fn->getASTContext();
SourceLoc insertionLoc;
// If there is a body macro, start at the beginning of it.
if (auto bodyBufferID = evaluateOrDefault(
ctx.evaluator, ExpandBodyMacroRequest{fn}, std::nullopt)) {
insertionLoc = ctx.SourceMgr.getRangeForBuffer(*bodyBufferID).getStart();
} else {
// If there is a parsed body, start at the beginning of it.
SourceRange range = fn->getBodySourceRange();
if (range.isValid()) {
insertionLoc = range.Start;
} else {
insertionLoc = fn->getEndLoc();
}
}
return CharSourceRange(insertionLoc, 0);
}
static CharSourceRange getExpansionInsertionRange(MacroRole role,
ASTNode target,
SourceManager &sourceMgr) {
switch (role) {
case MacroRole::Accessor: {
auto storage = cast<AbstractStorageDecl>(target.get<Decl *>());
auto bracesRange = storage->getBracesRange();
// Compute the location where the accessors will be added.
if (bracesRange.Start.isValid()) {
// We have braces already, so insert them inside the leading '{'.
return CharSourceRange(
Lexer::getLocForEndOfToken(sourceMgr, bracesRange.Start), 0);
} else if (auto initRange = getExplicitInitializerRange(storage)) {
// The accessor had an initializer, so the initializer (including
// the `=`) is replaced by the accessors.
return Lexer::getCharSourceRangeFromSourceRange(sourceMgr, *initRange);
} else {
// The accessors go at the end.
SourceLoc endLoc = storage->getEndLoc();
if (auto var = dyn_cast<VarDecl>(storage)) {
if (auto pattern = var->getParentPattern())
endLoc = pattern->getEndLoc();
}
return CharSourceRange(Lexer::getLocForEndOfToken(sourceMgr, endLoc), 0);
}
}
case MacroRole::MemberAttribute: {
SourceLoc startLoc;
if (auto valueDecl = dyn_cast<ValueDecl>(target.get<Decl *>()))
startLoc = valueDecl->getAttributeInsertionLoc(/*forModifier=*/true);
else
startLoc = target.getStartLoc();
return CharSourceRange(startLoc, 0);
}
case MacroRole::Member: {
// Semantically, we insert members right before the closing brace.
SourceLoc rightBraceLoc;
if (auto nominal = dyn_cast<NominalTypeDecl>(target.get<Decl *>())) {
rightBraceLoc = nominal->getBraces().End;
} else {
auto ext = cast<ExtensionDecl>(target.get<Decl *>());
rightBraceLoc = ext->getBraces().End;
}
return CharSourceRange(rightBraceLoc, 0);
}
case MacroRole::Peer: {
SourceLoc endLoc = target.getEndLoc();
if (auto var = dyn_cast<VarDecl>(target.get<Decl *>())) {
if (auto binding = var->getParentPatternBinding())
endLoc = binding->getEndLoc();
}
SourceLoc afterDeclLoc = Lexer::getLocForEndOfToken(sourceMgr, endLoc);
return CharSourceRange(afterDeclLoc, 0);
break;
}
case MacroRole::Conformance: {
SourceLoc afterDeclLoc =
Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc());
return CharSourceRange(afterDeclLoc, 0);
}
case MacroRole::Extension: {
SourceLoc afterDeclLoc =
Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc());
return CharSourceRange(afterDeclLoc, 0);
}
case MacroRole::Preamble: {
if (auto fn = dyn_cast<AbstractFunctionDecl>(target.get<Decl *>())) {
return getPreambleMacroOriginalRange(fn);
}
return CharSourceRange(Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc()), 0);
}
case MacroRole::Body: {
SourceLoc afterDeclLoc =
Lexer::getLocForEndOfToken(sourceMgr, target.getEndLoc());
return CharSourceRange(afterDeclLoc, 0);
}
case MacroRole::Expression:
case MacroRole::Declaration:
case MacroRole::CodeItem:
return Lexer::getCharSourceRangeFromSourceRange(sourceMgr,
target.getSourceRange());
}
llvm_unreachable("unhandled MacroRole");
}
static SourceFile *
createMacroSourceFile(std::unique_ptr<llvm::MemoryBuffer> buffer,
MacroRole role, ASTNode target, DeclContext *dc,
CustomAttr *attr) {
ASTContext &ctx = dc->getASTContext();
SourceManager &sourceMgr = ctx.SourceMgr;
// Dump macro expansions to standard output, if requested.
if (ctx.LangOpts.DumpMacroExpansions) {
llvm::errs() << buffer->getBufferIdentifier()
<< "\n------------------------------\n"
<< buffer->getBuffer()
<< "\n------------------------------\n";
}
CharSourceRange generatedOriginalSourceRange =
getExpansionInsertionRange(role, target, sourceMgr);
GeneratedSourceInfo::Kind generatedSourceKind =
getGeneratedSourceInfoKind(role);
// Create a new source buffer with the contents of the expanded macro.
unsigned macroBufferID = sourceMgr.addNewSourceBuffer(std::move(buffer));
auto macroBufferRange = sourceMgr.getRangeForBuffer(macroBufferID);
GeneratedSourceInfo sourceInfo{generatedSourceKind,
generatedOriginalSourceRange,
macroBufferRange,
target.getOpaqueValue(),
dc,
attr};
sourceMgr.setGeneratedSourceInfo(macroBufferID, sourceInfo);
// Create a source file to hold the macro buffer. This is automatically
// registered with the enclosing module.
auto macroSourceFile = new (ctx) SourceFile(
*dc->getParentModule(), SourceFileKind::MacroExpansion, macroBufferID,
/*parsingOpts=*/{}, /*isPrimary=*/false);
macroSourceFile->setImports(dc->getParentSourceFile()->getImports());
return macroSourceFile;
}
#if SWIFT_BUILD_SWIFT_SYNTAX
static uint8_t getRawMacroRole(MacroRole role) {
switch (role) {
case MacroRole::Expression: return 0;
case MacroRole::Declaration: return 1;
case MacroRole::Accessor: return 2;
case MacroRole::MemberAttribute: return 3;
case MacroRole::Member: return 4;
case MacroRole::Peer: return 5;
case MacroRole::CodeItem: return 7;
// Use the same raw macro role for conformance and extension
// in ASTGen.
case MacroRole::Conformance:
case MacroRole::Extension: return 8;
case MacroRole::Preamble: return 9;
case MacroRole::Body: return 10;
}
}
#endif // SWIFT_BUILD_SWIFT_SYNTAX
/// Evaluate the given freestanding macro expansion.
static SourceFile *
evaluateFreestandingMacro(FreestandingMacroExpansion *expansion,
StringRef discriminatorStr = "") {
auto *dc = expansion->getDeclContext();
ASTContext &ctx = dc->getASTContext();
SourceLoc loc = expansion->getPoundLoc();
auto moduleDecl = dc->getParentModule();
auto sourceFile = moduleDecl->getSourceFileContainingLocation(loc);
if (!sourceFile)
return nullptr;
MacroDecl *macro = cast<MacroDecl>(expansion->getMacroRef().getDecl());
auto macroRoles = macro->getMacroRoles();
assert(macroRoles.contains(MacroRole::Expression) ||
macroRoles.contains(MacroRole::Declaration) ||
macroRoles.contains(MacroRole::CodeItem));
if (isFromExpansionOfMacro(sourceFile, macro, MacroRole::Expression) ||
isFromExpansionOfMacro(sourceFile, macro, MacroRole::Declaration) ||
isFromExpansionOfMacro(sourceFile, macro, MacroRole::CodeItem)) {
ctx.Diags.diagnose(loc, diag::macro_recursive, macro->getName());
return nullptr;
}
// Evaluate the macro.
std::unique_ptr<llvm::MemoryBuffer> evaluatedSource;
/// The discriminator used for the macro.
LazyValue<std::string> discriminator([&]() -> std::string {
if (!discriminatorStr.empty())
return discriminatorStr.str();
#if SWIFT_BUILD_SWIFT_SYNTAX
Mangle::ASTMangler mangler;
return mangler.mangleMacroExpansion(expansion);
#else
return "";
#endif
});
auto macroDef = macro->getDefinition();
switch (macroDef.kind) {
case MacroDefinition::Kind::Undefined:
case MacroDefinition::Kind::Invalid:
// Already diagnosed as an error elsewhere.
return nullptr;
case MacroDefinition::Kind::Builtin: {
switch (macroDef.getBuiltinKind()) {
case BuiltinMacroKind::ExternalMacro:
ctx.Diags.diagnose(loc, diag::external_macro_outside_macro_definition);
return nullptr;
case BuiltinMacroKind::IsolationMacro:
// Create a buffer full of scratch space; this will be populated
// much later.
std::string scratchSpace(128, ' ');
evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy(
scratchSpace,
adjustMacroExpansionBufferName(*discriminator));
break;
}
break;
}
case MacroDefinition::Kind::Expanded: {
// Expand the definition with the given arguments.
auto result = expandMacroDefinition(macroDef.getExpanded(), macro,
expansion->getMacroRef().getSubstitutions(),
expansion->getArgs());
evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy(
result, adjustMacroExpansionBufferName(*discriminator));
break;
}
case MacroDefinition::Kind::External: {
// Retrieve the external definition of the macro.
auto external = macroDef.getExternalMacro();
ExternalMacroDefinitionRequest request{&ctx, external.moduleName,
external.macroTypeName};
auto externalDef =
evaluateOrDefault(ctx.evaluator, request,
ExternalMacroDefinition::error("request error"));
if (externalDef.isError()) {
ctx.Diags.diagnose(loc, diag::external_macro_not_found,
external.moduleName.str(),
external.macroTypeName.str(), macro->getName(),
externalDef.getErrorMessage());
macro->diagnose(diag::decl_declared_here, macro);
return nullptr;
}
// Code item macros require `CodeItemMacros` feature flag.
if (macroRoles.contains(MacroRole::CodeItem) &&
!ctx.LangOpts.hasFeature(Feature::CodeItemMacros)) {
ctx.Diags.diagnose(loc, diag::macro_experimental, "code item",
"CodeItemMacros");
return nullptr;
}
#if SWIFT_BUILD_SWIFT_SYNTAX
// Only one freestanding macro role is permitted, so look at the roles to
// figure out which one to use.
MacroRole macroRole =
macroRoles.contains(MacroRole::Expression) ? MacroRole::Expression
: macroRoles.contains(MacroRole::Declaration) ? MacroRole::Declaration
: MacroRole::CodeItem;
PrettyStackTraceFreestandingMacroExpansion debugStack(
"expanding freestanding macro", expansion);
// Builtin macros are handled via ASTGen.
auto *astGenSourceFile = sourceFile->getExportedSourceFile();
if (!astGenSourceFile)
return nullptr;
BridgedStringRef evaluatedSourceOut{nullptr, 0};
assert(!externalDef.isError());
swift_ASTGen_expandFreestandingMacro(
&ctx.Diags, externalDef.opaqueHandle,
static_cast<uint32_t>(externalDef.kind), discriminator->c_str(),
getRawMacroRole(macroRole), astGenSourceFile,
expansion->getSourceRange().Start.getOpaquePointerValue(),
&evaluatedSourceOut);
if (!evaluatedSourceOut.unbridged().data())
return nullptr;
evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy(
evaluatedSourceOut.unbridged(),
adjustMacroExpansionBufferName(*discriminator));
swift_ASTGen_freeBridgedString(evaluatedSourceOut);
break;
#else
ctx.Diags.diagnose(loc, diag::macro_unsupported);
return nullptr;
#endif
}
}
return createMacroSourceFile(std::move(evaluatedSource),
isa<MacroExpansionDecl>(expansion)
? MacroRole::Declaration
: MacroRole::Expression,
expansion->getASTNode(), dc,
/*attr=*/nullptr);
}
std::optional<unsigned> swift::expandMacroExpr(MacroExpansionExpr *mee) {
SourceFile *macroSourceFile = ::evaluateFreestandingMacro(mee);
if (!macroSourceFile)
return std::nullopt;
DeclContext *dc = mee->getDeclContext();
ASTContext &ctx = dc->getASTContext();
SourceManager &sourceMgr = ctx.SourceMgr;
auto macroBufferID = *macroSourceFile->getBufferID();
auto macroBufferRange = sourceMgr.getRangeForBuffer(macroBufferID);
// Handle builtin macro definitions by producing the expression we
// need without parsing the buffer.
auto expandedType = mee->getType();
Expr *expandedExpr = nullptr;
auto macro = cast<MacroDecl>(mee->getMacroRef().getDecl());
switch (auto definition = macro->getDefinition()) {
case MacroDefinition::Kind::Expanded:
case MacroDefinition::Kind::External:
case MacroDefinition::Kind::Invalid:
case MacroDefinition::Kind::Undefined:
break;
case MacroDefinition::Kind::Builtin:
switch (definition.getBuiltinKind()) {
case BuiltinMacroKind::ExternalMacro:
break;
case BuiltinMacroKind::IsolationMacro:
expandedExpr = new (ctx) CurrentContextIsolationExpr(
macroBufferRange.getStart(), expandedType);
break;
}
}
if (!expandedExpr) {
// Parse the macro source file and retrieve the parsed expression
// from the list of top-level items.
auto topLevelItems = macroSourceFile->getTopLevelItems();
if (topLevelItems.size() != 1) {
ctx.Diags.diagnose(
macroBufferRange.getStart(), diag::expected_macro_expansion_expr);
return macroBufferID;
}
auto codeItem = topLevelItems.front();
if (auto *expr = codeItem.dyn_cast<Expr *>())
expandedExpr = expr;
} else {
// We produced the expanded expression via a builtin macro above,
// so there is nothing more we need to do.
}
if (!expandedExpr) {
ctx.Diags.diagnose(
macroBufferRange.getStart(), diag::expected_macro_expansion_expr);
return macroBufferID;
}
// Type-check the expanded expression.
// FIXME: Would like to pass through type checking options like "discarded"
// that are captured by TypeCheckExprOptions.
constraints::ContextualTypeInfo contextualType {
TypeLoc::withoutLoc(expandedType),
// FIXME: Add a contextual type purpose for macro expansion.
ContextualTypePurpose::CTP_CoerceOperand
};
PrettyStackTraceExpr debugStack(
ctx, "type checking expanded macro", expandedExpr);
Type realExpandedType = TypeChecker::typeCheckExpression(
expandedExpr, dc, contextualType);
if (!realExpandedType)
return macroBufferID;
assert((expandedType->isEqual(realExpandedType) ||
realExpandedType->hasError()) &&
"Type checking changed the result type?");
mee->setRewritten(expandedExpr);
return macroBufferID;
}
/// Expands the given macro expansion declaration.
std::optional<unsigned>
swift::expandFreestandingMacro(MacroExpansionDecl *med) {
SourceFile *macroSourceFile = ::evaluateFreestandingMacro(med);
if (!macroSourceFile)
return std::nullopt;
MacroDecl *macro = cast<MacroDecl>(med->getMacroRef().getDecl());
auto macroRoles = macro->getMacroRoles();
assert(macroRoles.contains(MacroRole::Declaration) ||
macroRoles.contains(MacroRole::CodeItem));
DeclContext *dc = med->getDeclContext();
validateMacroExpansion(macroSourceFile, macro,
/*attachedTo*/nullptr,
macroRoles.contains(MacroRole::Declaration) ?
MacroRole::Declaration :
MacroRole::CodeItem);
PrettyStackTraceDecl debugStack(
"type checking expanded declaration macro", med);
auto topLevelItems = macroSourceFile->getTopLevelItems();
for (auto item : topLevelItems) {
if (auto *decl = item.dyn_cast<Decl *>())
decl->setDeclContext(dc);
}
return *macroSourceFile->getBufferID();
}
static SourceFile *evaluateAttachedMacro(MacroDecl *macro, Decl *attachedTo,
CustomAttr *attr,
bool passParentContext, MacroRole role,
ArrayRef<ProtocolDecl *> conformances = {},
StringRef discriminatorStr = "") {
DeclContext *dc;
if (role == MacroRole::Peer) {
dc = attachedTo->getDeclContext();
} else if (role == MacroRole::Conformance || role == MacroRole::Extension) {
// Conformance macros always expand to extensions at file-scope.
dc = attachedTo->getDeclContext()->getParentSourceFile();
} else {
dc = attachedTo->getInnermostDeclContext();
}
// FIXME: compatibility hack for the transition from property wrapper
// to macro for TaskLocal.
//
// VarDecls with `@_projectedValueProperty` have already had the property
// wrapper transform applied. This only impacts swiftinterfaces, and if
// a swiftinterface was produced against a Concurrency library that does
// not declare TaskLocal as a macro, we need to ignore the macro to avoid
// producing duplicate declarations. This is only needed temporarily until
// all swiftinterfaces have been built against the Concurrency library
// containing the new macro declaration.
if (auto *var = dyn_cast<VarDecl>(attachedTo)) {
if (var->getAttrs().getAttribute<ProjectedValuePropertyAttr>()) {
return nullptr;
}
}
ASTContext &ctx = dc->getASTContext();
auto moduleDecl = dc->getParentModule();
auto attrSourceFile =
moduleDecl->getSourceFileContainingLocation(attr->AtLoc);
if (!attrSourceFile)
return nullptr;
auto declSourceFile =
moduleDecl->getSourceFileContainingLocation(attachedTo->getStartLoc());
if (!declSourceFile)
return nullptr;
Decl *parentDecl = nullptr;
SourceFile *parentDeclSourceFile = nullptr;
if (passParentContext) {
parentDecl = attachedTo->getDeclContext()->getAsDecl();
if (!parentDecl)
return nullptr;
parentDeclSourceFile =
moduleDecl->getSourceFileContainingLocation(parentDecl->getLoc());
if (!parentDeclSourceFile)
return nullptr;
}
if (isFromExpansionOfMacro(attrSourceFile, macro, role) ||
isFromExpansionOfMacro(declSourceFile, macro, role) ||
isFromExpansionOfMacro(parentDeclSourceFile, macro, role)) {
attachedTo->diagnose(diag::macro_recursive, macro->getName());
return nullptr;
}
// Evaluate the macro.
std::unique_ptr<llvm::MemoryBuffer> evaluatedSource;
/// The discriminator used for the macro.
LazyValue<std::string> discriminator([&]() -> std::string {
if (!discriminatorStr.empty())
return discriminatorStr.str();
#if SWIFT_BUILD_SWIFT_SYNTAX
Mangle::ASTMangler mangler;
return mangler.mangleAttachedMacroExpansion(attachedTo, attr, role);
#else
return "";
#endif
});
std::string extendedType;
{
llvm::raw_string_ostream OS(extendedType);
if (role == MacroRole::Extension || role == MacroRole::Conformance) {
auto *nominal = dyn_cast<NominalTypeDecl>(attachedTo);
PrintOptions options;
options.FullyQualifiedExtendedTypesIfAmbiguous = true;
nominal->getDeclaredType()->print(OS, options);
} else {
OS << "";
}
}
std::string conformanceList;
{
llvm::raw_string_ostream OS(conformanceList);
if (role == MacroRole::Extension || role == MacroRole::Member) {
llvm::interleave(
conformances,
[&](const ProtocolDecl *protocol) {
protocol->getDeclaredType()->print(OS);
},
[&] { OS << ", "; }
);
} else {
OS << "";
}
}
auto macroDef = macro->getDefinition();
switch (macroDef.kind) {
case MacroDefinition::Kind::Undefined:
case MacroDefinition::Kind::Invalid:
// Already diagnosed as an error elsewhere.
return nullptr;
case MacroDefinition::Kind::Builtin: {
switch (macroDef.getBuiltinKind()) {
case BuiltinMacroKind::ExternalMacro:
case BuiltinMacroKind::IsolationMacro:
// FIXME: Error here.
return nullptr;
}
}
case MacroDefinition::Kind::Expanded: {
// Expand the definition with the given arguments.
auto result = expandMacroDefinition(
macroDef.getExpanded(), macro,
/*genericArgs=*/{}, // attached macros don't have generic parameters
attr->getArgs());
evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy(
result, adjustMacroExpansionBufferName(*discriminator));
break;
}
case MacroDefinition::Kind::External: {
// Retrieve the external definition of the macro.
auto external = macroDef.getExternalMacro();
ExternalMacroDefinitionRequest request{
&ctx, external.moduleName, external.macroTypeName
};
auto externalDef =
evaluateOrDefault(ctx.evaluator, request,
ExternalMacroDefinition::error("failed request"));
if (externalDef.isError()) {
attachedTo->diagnose(diag::external_macro_not_found,
external.moduleName.str(),
external.macroTypeName.str(), macro->getName(),
externalDef.getErrorMessage());
macro->diagnose(diag::decl_declared_here, macro);
return nullptr;
}
#if SWIFT_BUILD_SWIFT_SYNTAX
PrettyStackTraceDecl debugStack("expanding attached macro", attachedTo);
auto *astGenAttrSourceFile = attrSourceFile->getExportedSourceFile();
if (!astGenAttrSourceFile)
return nullptr;
auto *astGenDeclSourceFile = declSourceFile->getExportedSourceFile();
if (!astGenDeclSourceFile)
return nullptr;
void *astGenParentDeclSourceFile = nullptr;
const void *parentDeclLoc = nullptr;
if (passParentContext) {
astGenParentDeclSourceFile =
parentDeclSourceFile->getExportedSourceFile();
if (!astGenParentDeclSourceFile)
return nullptr;
parentDeclLoc = parentDecl->getStartLoc().getOpaquePointerValue();
}
Decl *searchDecl = attachedTo;
if (auto var = dyn_cast<VarDecl>(attachedTo))
searchDecl = var->getParentPatternBinding();
BridgedStringRef evaluatedSourceOut{nullptr, 0};
assert(!externalDef.isError());
swift_ASTGen_expandAttachedMacro(
&ctx.Diags, externalDef.opaqueHandle,
static_cast<uint32_t>(externalDef.kind), discriminator->c_str(),
extendedType.c_str(), conformanceList.c_str(), getRawMacroRole(role),
astGenAttrSourceFile, attr->AtLoc.getOpaquePointerValue(),
astGenDeclSourceFile, searchDecl->getStartLoc().getOpaquePointerValue(),
astGenParentDeclSourceFile, parentDeclLoc, &evaluatedSourceOut);
if (!evaluatedSourceOut.unbridged().data())
return nullptr;
evaluatedSource = llvm::MemoryBuffer::getMemBufferCopy(
evaluatedSourceOut.unbridged(),
adjustMacroExpansionBufferName(*discriminator));
swift_ASTGen_freeBridgedString(evaluatedSourceOut);
break;
#else
attachedTo->diagnose(diag::macro_unsupported);
return nullptr;
#endif
}
}
SourceFile *macroSourceFile = createMacroSourceFile(
std::move(evaluatedSource), role, attachedTo, dc, attr);
validateMacroExpansion(macroSourceFile, macro,
dyn_cast<ValueDecl>(attachedTo), role);
return macroSourceFile;
}
bool swift::accessorMacroOnlyIntroducesObservers(
MacroDecl *macro,
const MacroRoleAttr *attr
) {
// Will this macro introduce observers?
bool foundObserver = false;
for (auto name : attr->getNames()) {
if (name.getKind() == MacroIntroducedDeclNameKind::Named &&
(name.getName().getBaseName().userFacingName() == "willSet" ||
name.getName().getBaseName().userFacingName() == "didSet" ||
name.getName().getBaseName().isConstructor())) {
foundObserver = true;
} else {
// Introduces something other than an observer.
return false;
}
}
if (foundObserver)
return true;
// WORKAROUND: Older versions of the Observation library make
// `ObservationIgnored` an accessor macro that implies that it makes a
// stored property computed. Override that, because we know it produces
// nothing.
if (macro->getName().getBaseName().userFacingName() == "ObservationIgnored") {
return true;
}
return false;
}
bool swift::accessorMacroIntroducesInitAccessor(
MacroDecl *macro, const MacroRoleAttr *attr
) {
for (auto name : attr->getNames()) {
if (name.getKind() == MacroIntroducedDeclNameKind::Named &&
(name.getName().getBaseName().isConstructor()))
return true;
}
return false;
}
std::optional<unsigned> swift::expandAccessors(AbstractStorageDecl *storage,
CustomAttr *attr,
MacroDecl *macro) {
if (auto var = dyn_cast<VarDecl>(storage)) {
// Check that the variable is part of a single-variable pattern.
auto binding = var->getParentPatternBinding();
if (binding && binding->getSingleVar() != var) {
var->diagnose(diag::accessor_macro_not_single_var, macro->getName());
return std::nullopt;
}
}
// Evaluate the macro.
auto macroSourceFile =
::evaluateAttachedMacro(macro, storage, attr,
/*passParentContext=*/false, MacroRole::Accessor);
if (!macroSourceFile)
return std::nullopt;
PrettyStackTraceDecl debugStack(
"type checking expanded accessor macro", storage);
// Trigger parsing of the sequence of accessor declarations. This has the
// side effect of registering those accessor declarations with the storage
// declaration, so there is nothing further to do.
AccessorDecl *foundNonObservingAccessor = nullptr;
AccessorDecl *foundNonObservingAccessorInMacro = nullptr;
AccessorDecl *foundInitAccessor = nullptr;
for (auto accessor : storage->getAllAccessors()) {
if (accessor->isInitAccessor()) {
if (!foundInitAccessor)
foundInitAccessor = accessor;
continue;
}
if (!accessor->isObservingAccessor()) {
if (!foundNonObservingAccessor)
foundNonObservingAccessor = accessor;
if (!foundNonObservingAccessorInMacro &&
accessor->isInMacroExpansionInContext())
foundNonObservingAccessorInMacro = accessor;
}
}
auto roleAttr = macro->getMacroRoleAttr(MacroRole::Accessor);
bool expectObservers = accessorMacroOnlyIntroducesObservers(macro, roleAttr);
if (foundNonObservingAccessorInMacro) {
// If any non-observing accessor was added, mark the initializer as
// subsumed unless it has init accessor, because the initializer in
// such cases could be used for memberwise initialization.
if (auto var = dyn_cast<VarDecl>(storage)) {
if (auto binding = var->getParentPatternBinding();
!var->getAccessor(AccessorKind::Init)) {
unsigned index = binding->getPatternEntryIndexForVarDecl(var);
binding->setInitializerSubsumed(index);
}
}
// Also remove didSet and willSet, because they are subsumed by a
// macro expansion that turns a stored property into a computed one.
if (auto accessor = storage->getParsedAccessor(AccessorKind::WillSet))
storage->removeAccessor(accessor);
if (auto accessor = storage->getParsedAccessor(AccessorKind::DidSet))
storage->removeAccessor(accessor);
}
// If the macro told us to expect only observing accessors, but the macro
// produced a non-observing accessor, it could have converted a stored
// property into a computed one without telling us pre-expansion. Produce
// an error to prevent this.
if (expectObservers && foundNonObservingAccessorInMacro) {
storage->diagnose(
diag::macro_nonobserver_unexpected_in_expansion, macro->getName(),
foundNonObservingAccessorInMacro->getDescriptiveKind());
}
// We expected to get a non-observing accessor, but there isn't one (from
// the macro or elsewhere), meaning that we counted on this macro to make
// this stored property into a a computed property... but it didn't.
// Produce an error.
if (!expectObservers && !foundNonObservingAccessor) {
storage->diagnose(
diag::macro_nonobserving_accessor_missing_from_expansion,
macro->getName());
}
// 'init' accessors must be documented in the macro role attribute.
if (foundInitAccessor &&
!accessorMacroIntroducesInitAccessor(macro, roleAttr)) {
storage->diagnose(
diag::macro_init_accessor_not_documented, macro->getName());
// FIXME: Add the appropriate "names: named(init)".
}
return macroSourceFile->getBufferID();
}
ArrayRef<unsigned> ExpandAccessorMacros::evaluate(
Evaluator &evaluator, AbstractStorageDecl *storage
) const {
llvm::SmallVector<unsigned, 1> bufferIDs;
storage->forEachAttachedMacro(MacroRole::Accessor,
[&](CustomAttr *customAttr, MacroDecl *macro) {
if (auto bufferID = expandAccessors(
storage, customAttr, macro))
bufferIDs.push_back(*bufferID);
});
return storage->getASTContext().AllocateCopy(bufferIDs);
}
ArrayRef<unsigned> ExpandPreambleMacroRequest::evaluate(
Evaluator &evaluator, AbstractFunctionDecl *fn) const {
llvm::SmallVector<unsigned, 1> bufferIDs;
fn->forEachAttachedMacro(MacroRole::Preamble,
[&](CustomAttr *customAttr, MacroDecl *macro) {
auto macroSourceFile = ::evaluateAttachedMacro(
macro, fn, customAttr, false, MacroRole::Preamble);
if (!macroSourceFile)
return;
if (auto bufferID = macroSourceFile->getBufferID())
bufferIDs.push_back(*bufferID);
});
std::reverse(bufferIDs.begin(), bufferIDs.end());
return fn->getASTContext().AllocateCopy(bufferIDs);
}
std::optional<unsigned>
ExpandBodyMacroRequest::evaluate(Evaluator &evaluator,
AbstractFunctionDecl *fn) const {
std::optional<unsigned> bufferID;
fn->forEachAttachedMacro(MacroRole::Body,
[&](CustomAttr *customAttr, MacroDecl *macro) {
// FIXME: Should we complain if we already expanded a body macro?
if (bufferID)
return;
auto macroSourceFile = ::evaluateAttachedMacro(
macro, fn, customAttr, false, MacroRole::Body);
if (!macroSourceFile)
return;
bufferID = macroSourceFile->getBufferID();
});
return bufferID;
}
std::optional<unsigned>
swift::expandAttributes(CustomAttr *attr, MacroDecl *macro, Decl *member) {
// Evaluate the macro.
auto macroSourceFile = ::evaluateAttachedMacro(macro, member, attr,
/*passParentContext=*/true,
MacroRole::MemberAttribute);
if (!macroSourceFile)
return std::nullopt;
PrettyStackTraceDecl debugStack(
"type checking expanded declaration macro", member);
auto topLevelDecls = macroSourceFile->getTopLevelDecls();
for (auto decl : topLevelDecls) {
// Add the new attributes to the semantic attribute list.
SmallVector<DeclAttribute *, 2> attrs(decl->getAttrs().begin(),
decl->getAttrs().end());
for (auto *attr : attrs) {
member->getAttrs().add(attr);
}
}
return macroSourceFile->getBufferID();
}
// Collect the protocol conformances that the macro asked about but were
// not already present on the declaration.
static TinyPtrVector<ProtocolDecl *> getIntroducedConformances(
NominalTypeDecl *nominal, MacroRole role, MacroDecl *macro,
SmallVectorImpl<ProtocolDecl *> *potentialConformances = nullptr) {
SmallVector<ProtocolDecl *, 2> potentialConformancesBuffer;
if (!potentialConformances)
potentialConformances = &potentialConformancesBuffer;
macro->getIntroducedConformances(nominal, role, *potentialConformances);
TinyPtrVector<ProtocolDecl *> introducedConformances;
for (auto protocol : *potentialConformances) {
SmallVector<ProtocolConformance *, 2> existingConformances;
nominal->lookupConformance(protocol, existingConformances);
bool hasExistingConformance = llvm::any_of(
existingConformances,
[&](ProtocolConformance *conformance) {
return conformance->getSourceKind() !=
ConformanceEntryKind::PreMacroExpansion;
});
if (!hasExistingConformance) {
introducedConformances.push_back(protocol);
}
}
return introducedConformances;
}
std::optional<unsigned> swift::expandMembers(CustomAttr *attr, MacroDecl *macro,
Decl *decl) {
auto nominal = dyn_cast<NominalTypeDecl>(decl);
if (!nominal) {
auto ext = dyn_cast<ExtensionDecl>(decl);
if (!ext)
return std::nullopt;
nominal = ext->getExtendedNominal();
if (!nominal)
return std::nullopt;
}
auto introducedConformances = getIntroducedConformances(
nominal, MacroRole::Member, macro);
// Evaluate the macro.
auto macroSourceFile =
::evaluateAttachedMacro(macro, decl, attr,
/*passParentContext=*/false, MacroRole::Member,
introducedConformances);
if (!macroSourceFile)
return std::nullopt;
PrettyStackTraceDecl debugStack(
"type checking expanded declaration macro", decl);
auto topLevelDecls = macroSourceFile->getTopLevelDecls();
for (auto member : topLevelDecls) {
// Note that synthesized members are not considered implicit. They have
// proper source ranges that should be validated, and ASTScope does not
// expand implicit scopes to the parent scope tree.
if (auto *nominal = dyn_cast<NominalTypeDecl>(decl)) {
nominal->addMember(member);
} else if (auto *extension = dyn_cast<ExtensionDecl>(decl)) {
extension->addMember(member);
}
}
return macroSourceFile->getBufferID();
}
std::optional<unsigned> swift::expandPeers(CustomAttr *attr, MacroDecl *macro,
Decl *decl) {
auto macroSourceFile =
::evaluateAttachedMacro(macro, decl, attr,
/*passParentContext=*/false, MacroRole::Peer);
if (!macroSourceFile)
return std::nullopt;
PrettyStackTraceDecl debugStack("applying expanded peer macro", decl);
return macroSourceFile->getBufferID();
}
ArrayRef<unsigned>
ExpandExtensionMacros::evaluate(Evaluator &evaluator,
NominalTypeDecl *nominal) const {
SmallVector<unsigned, 2> bufferIDs;
for (auto customAttrConst :
nominal->getExpandedAttrs().getAttributes<CustomAttr>()) {
auto customAttr = const_cast<CustomAttr *>(customAttrConst);
auto *macro = nominal->getResolvedMacro(customAttr);
if (!macro)
continue;
// Prefer the extension role
MacroRole role;
if (macro->getMacroRoles().contains(MacroRole::Extension)) {
role = MacroRole::Extension;
} else if (macro->getMacroRoles().contains(MacroRole::Conformance)) {
role = MacroRole::Conformance;
} else {
continue;
}
if (auto bufferID = expandExtensions(customAttr, macro,
role, nominal))
bufferIDs.push_back(*bufferID);
}
return nominal->getASTContext().AllocateCopy(bufferIDs);
}
std::optional<unsigned> swift::expandExtensions(CustomAttr *attr,
MacroDecl *macro,
MacroRole role,
NominalTypeDecl *nominal) {
if (nominal->getDeclContext()->isLocalContext()) {
nominal->diagnose(diag::local_extension_macro);
return std::nullopt;
}
SmallVector<ProtocolDecl *, 2> potentialConformances;
auto introducedConformances = getIntroducedConformances(
nominal, MacroRole::Extension, macro, &potentialConformances);
auto macroSourceFile = ::evaluateAttachedMacro(macro, nominal, attr,
/*passParentContext=*/false,
role, introducedConformances);
if (!macroSourceFile)
return std::nullopt;
PrettyStackTraceDecl debugStack(
"applying expanded extension macro", nominal);
auto topLevelDecls = macroSourceFile->getTopLevelDecls();
for (auto *decl : topLevelDecls) {
auto *extension = dyn_cast<ExtensionDecl>(decl);
if (!extension)
continue;
// Bind the extension to the original nominal type.
extension->setExtendedNominal(nominal);
nominal->addExtension(extension);
// Most other macro-generated declarations are visited through calling
// 'visitAuxiliaryDecls' on the original declaration the macro is attached
// to. We don't do this for macro-generated extensions, because the
// extension is not a peer of the original declaration. Instead of
// requiring all callers of 'visitAuxiliaryDecls' to understand the
// hoisting behavior of macro-generated extensions, we make the
// extension accessible through 'getTopLevelDecls()'.
if (auto file = dyn_cast<FileUnit>(
decl->getDeclContext()->getModuleScopeContext()))
file->getOrCreateSynthesizedFile().addTopLevelDecl(extension);
// Don't validate documented conformances for the 'conformance' role.
if (role == MacroRole::Conformance)
continue;
// Extension macros can only add conformances that are documented by
// the `@attached(extension)` attribute.
auto inheritedTypes = extension->getInherited();
for (auto i : inheritedTypes.getIndices()) {
auto constraint =
TypeResolution::forInterface(
extension->getDeclContext(),
TypeResolverContext::GenericRequirement,
/*unboundTyOpener*/ nullptr,
/*placeholderHandler*/ nullptr,
/*packElementOpener*/ nullptr)
.resolveType(inheritedTypes.getTypeRepr(i));
// Already diagnosed or will be diagnosed later.
if (constraint->is<ErrorType>() || !constraint->isConstraintType())
continue;
std::function<bool(Type)> isUndocumentedConformance =
[&](Type constraint) -> bool {
if (auto *proto = constraint->getAs<ParameterizedProtocolType>())
return !llvm::is_contained(potentialConformances,
proto->getProtocol());
if (auto *proto = constraint->getAs<ProtocolType>())
return !llvm::is_contained(potentialConformances,
proto->getDecl());
return llvm::any_of(
constraint->castTo<ProtocolCompositionType>()->getMembers(),
isUndocumentedConformance);
};
if (isUndocumentedConformance(constraint)) {
extension->diagnose(
diag::undocumented_conformance_in_expansion,
constraint, macro->getBaseName());
extension->setInvalid();
}
}
}
return macroSourceFile->getBufferID();
}
/// Emits an error and returns \c true if the maro reference may
/// introduce arbitrary names at global scope.
static bool diagnoseArbitraryGlobalNames(DeclContext *dc,
UnresolvedMacroReference macroRef,
MacroRole macroRole) {
auto &ctx = dc->getASTContext();
assert(macroRole == MacroRole::Declaration ||
macroRole == MacroRole::Peer);
if (!dc->isModuleScopeContext())
return false;
bool isInvalid = false;
namelookup::forEachPotentialResolvedMacro(
dc, macroRef.getMacroName(), macroRole,
[&](MacroDecl *decl, const MacroRoleAttr *attr) {
if (!isInvalid &&
attr->hasNameKind(MacroIntroducedDeclNameKind::Arbitrary)) {
ctx.Diags.diagnose(macroRef.getSigilLoc(),
diag::global_arbitrary_name,
getMacroRoleString(macroRole));
isInvalid = true;
// If this is an attached macro, mark the attribute as invalid
// to avoid diagnosing an unknown attribute later.
if (auto *attr = macroRef.getAttr()) {
attr->setInvalid();
}
}
});
return isInvalid;
}
ConcreteDeclRef ResolveMacroRequest::evaluate(Evaluator &evaluator,
UnresolvedMacroReference macroRef,
DeclContext *dc) const {
// Macro expressions and declarations have their own stored macro
// reference. Use it if it's there.
if (auto *expansion = macroRef.getFreestanding()) {
if (auto ref = expansion->getMacroRef())
return ref;
}
auto &ctx = dc->getASTContext();
auto roles = macroRef.getMacroRoles();
// When a macro is not found for a custom attribute, it may be a non-macro.
// So bail out to prevent diagnostics from the contraint system.
if (macroRef.getAttr()) {
auto foundMacros = namelookup::lookupMacros(dc, macroRef.getModuleName(),
macroRef.getMacroName(), roles);
if (foundMacros.empty())
return ConcreteDeclRef();
}
// Freestanding and peer macros applied at top-level scope cannot introduce
// arbitrary names. Introducing arbitrary names means that any lookup
// into this scope must expand the macro. This is a problem, because
// resolving the macro can invoke type checking other declarations, e.g.
// anything that the macro arguments depend on. If _anything_ the macro
// depends on performs name unqualified name lookup, e.g. type resolution,
// we'll get circularity errors. It's better to prevent this by banning
// these macros at global scope if any of the macro candidates introduce
// arbitrary names.
if (diagnoseArbitraryGlobalNames(dc, macroRef, MacroRole::Declaration) ||
diagnoseArbitraryGlobalNames(dc, macroRef, MacroRole::Peer))
return ConcreteDeclRef();
// If we already have a MacroExpansionExpr, use that. Otherwise,
// create one.
MacroExpansionExpr *macroExpansion;
if (auto *expansion = macroRef.getFreestanding()) {
if (auto *expr = dyn_cast<MacroExpansionExpr>(expansion)) {
macroExpansion = expr;
} else {
macroExpansion = new (ctx) MacroExpansionExpr(
dc, expansion->getExpansionInfo(), roles);
}
} else {
SourceRange genericArgsRange = macroRef.getGenericArgsRange();
macroExpansion = MacroExpansionExpr::create(
dc, macroRef.getSigilLoc(), macroRef.getMacroName(),
macroRef.getMacroNameLoc(), genericArgsRange.Start,
macroRef.getGenericArgs(), genericArgsRange.End,
macroRef.getArgs(), roles);
}
Expr *result = macroExpansion;
TypeChecker::typeCheckExpression(
result, dc, {}, TypeCheckExprFlags::DisableMacroExpansions);
// If we couldn't resolve a macro decl, the attribute is invalid.
if (!macroExpansion->getMacroRef() && macroRef.getAttr())
macroRef.getAttr()->setInvalid();
// Macro expressions and declarations have their own stored macro
// reference. If we got a reference, store it there, too.
// FIXME: This duplication of state is really unfortunate.
if (auto ref = macroExpansion->getMacroRef()) {
if (auto *expansion = macroRef.getFreestanding()) {
expansion->setMacroRef(ref);
}
}
return macroExpansion->getMacroRef();
}
ArrayRef<Type>
ResolveMacroConformances::evaluate(Evaluator &evaluator,
const MacroRoleAttr *attr,
const Decl *decl) const {
auto *dc = decl->getDeclContext();
auto &ctx = dc->getASTContext();
SmallVector<Type, 2> protocols;
for (auto *typeExpr : attr->getConformances()) {
if (auto *typeRepr = typeExpr->getTypeRepr()) {
auto resolved =
TypeResolution::forInterface(
dc, TypeResolverContext::GenericRequirement,
/*unboundTyOpener*/ nullptr,
/*placeholderHandler*/ nullptr,
/*packElementOpener*/ nullptr)
.resolveType(typeRepr);
if (resolved->is<ErrorType>())
continue;
if (!resolved->isConstraintType()) {
diagnoseAndRemoveAttr(
decl, attr,
diag::extension_macro_invalid_conformance,
resolved);
continue;
}
typeExpr->setType(MetatypeType::get(resolved));
protocols.push_back(resolved);
} else {
// If there's no type repr, we already have a resolved instance
// type, e.g. because the type expr was deserialized.
protocols.push_back(typeExpr->getInstanceType());
}
}
return ctx.AllocateCopy(protocols);
}
// MARK: for IDE.
SourceFile *swift::evaluateAttachedMacro(MacroDecl *macro, Decl *attachedTo,
CustomAttr *attr,
bool passParentContext, MacroRole role,
StringRef discriminator) {
return ::evaluateAttachedMacro(macro, attachedTo, attr, passParentContext,
role, {}, discriminator);
}
SourceFile *
swift::evaluateFreestandingMacro(FreestandingMacroExpansion *expansion,
StringRef discriminator) {
return ::evaluateFreestandingMacro(expansion, discriminator);
}
|