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
|
//===--- BuilderTransform.cpp - Result-builder transformation -----------===//
//
// 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 routines associated with the result-builder
// transformation.
//
//===----------------------------------------------------------------------===//
#include "MiscDiagnostics.h"
#include "TypeCheckAvailability.h"
#include "TypeChecker.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Sema/ConstraintSystem.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Sema/SolutionResult.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include <iterator>
#include <map>
#include <memory>
#include <tuple>
#include <utility>
using namespace swift;
using namespace constraints;
namespace {
/// Find the first #available condition within the statement condition,
/// or return NULL if there isn't one.
const StmtConditionElement *findAvailabilityCondition(StmtCondition stmtCond) {
for (const auto &cond : stmtCond) {
switch (cond.getKind()) {
case StmtConditionElement::CK_Boolean:
case StmtConditionElement::CK_PatternBinding:
case StmtConditionElement::CK_HasSymbol:
continue;
case StmtConditionElement::CK_Availability:
return &cond;
break;
}
}
return nullptr;
}
class ResultBuilderTransform
: private StmtVisitor<ResultBuilderTransform, NullablePtr<Stmt>,
NullablePtr<VarDecl>> {
friend StmtVisitor<ResultBuilderTransform, NullablePtr<Stmt>,
NullablePtr<VarDecl>>;
using UnsupportedElt = SkipUnhandledConstructInResultBuilder::UnhandledNode;
ASTContext &ctx;
DeclContext *dc;
ResultBuilder builder;
/// The source range of the body.
SourceRange bodyRange;
/// The result type of this result builder body.
Type ResultType;
/// The first recorded unsupported element discovered by the transformation.
UnsupportedElt FirstUnsupported;
public:
ResultBuilderTransform(ConstraintSystem &cs, DeclContext *dc,
SourceRange bodyRange, Type builderType, Type resultTy)
: ctx(cs.getASTContext()), dc(dc), builder(cs, dc, builderType),
bodyRange(bodyRange), ResultType(resultTy) {}
UnsupportedElt getUnsupportedElement() const { return FirstUnsupported; }
BraceStmt *apply(BraceStmt *braceStmt) {
auto newBody = visitBraceStmt(braceStmt, /*bodyVar=*/nullptr);
if (!newBody)
return nullptr;
return castToStmt<BraceStmt>(newBody.get());
}
VarDecl *getBuilderSelf() const { return builder.getBuilderSelf(); }
protected:
NullablePtr<Stmt> failTransform(UnsupportedElt unsupported) {
recordUnsupported(unsupported);
return nullptr;
}
VarDecl *recordVar(PatternBindingDecl *PB,
SmallVectorImpl<ASTNode> &container) {
container.push_back(PB);
container.push_back(PB->getSingleVar());
return PB->getSingleVar();
}
VarDecl *captureExpr(Expr *expr, SmallVectorImpl<ASTNode> &container) {
auto *var = builder.buildVar(expr->getStartLoc());
Pattern *pattern = NamedPattern::createImplicit(ctx, var);
auto *PB = PatternBindingDecl::createImplicit(
ctx, StaticSpellingKind::None, pattern, expr, dc, var->getStartLoc());
return recordVar(PB, container);
}
VarDecl *buildPlaceholderVar(SourceLoc loc,
SmallVectorImpl<ASTNode> &container,
Type type = Type(), Expr *initExpr = nullptr) {
auto *var = builder.buildVar(loc);
Pattern *placeholder = TypedPattern::createImplicit(
ctx, NamedPattern::createImplicit(ctx, var),
type ? type : PlaceholderType::get(ctx, var));
auto *PB = PatternBindingDecl::createImplicit(
ctx, StaticSpellingKind::None, placeholder, /*init=*/initExpr, dc,
var->getStartLoc());
return recordVar(PB, container);
}
AssignExpr *buildAssignment(VarDecl *dst, VarDecl *src) {
auto *dstRef = builder.buildVarRef(dst, /*Loc=*/SourceLoc());
auto *srcRef = builder.buildVarRef(src, /*Loc=*/SourceLoc());
return new (ctx) AssignExpr(dstRef, /*EqualLoc=*/SourceLoc(), srcRef,
/*Implicit=*/true);
}
AssignExpr *buildAssignment(VarDecl *dst, Expr *srcExpr) {
auto *dstRef = builder.buildVarRef(dst, /*Loc=*/SourceLoc());
return new (ctx) AssignExpr(dstRef, /*EqualLoc=*/SourceLoc(), srcExpr,
/*implicit=*/true);
}
void recordUnsupported(UnsupportedElt node) {
if (!FirstUnsupported)
FirstUnsupported = node;
}
#define UNSUPPORTED_STMT(StmtClass) \
NullablePtr<Stmt> visit##StmtClass##Stmt(StmtClass##Stmt *stmt, \
NullablePtr<VarDecl> var) { \
return failTransform(stmt); \
}
/// Visit the element of a brace statement, returning \c None if the element
/// was transformed successfully, or an unsupported element if the element
/// cannot be handled.
std::optional<UnsupportedElt>
transformBraceElement(ASTNode element, SmallVectorImpl<ASTNode> &newBody,
SmallVectorImpl<Expr *> &buildBlockArguments) {
if (auto *returnStmt = getAsStmt<ReturnStmt>(element)) {
assert(returnStmt->isImplicit());
element = returnStmt->getResult();
}
// Unwrap an implicit ThenStmt.
if (auto *thenStmt = getAsStmt<ThenStmt>(element)) {
if (thenStmt->isImplicit())
element = thenStmt->getResult();
}
if (auto *decl = element.dyn_cast<Decl *>()) {
switch (decl->getKind()) {
// Just ignore #if; the chosen children should appear in
// the surrounding context. This isn't good for source
// tools but it at least works.
case DeclKind::IfConfig:
// Skip #warning/#error; we'll handle them when applying
// the builder.
case DeclKind::PoundDiagnostic:
case DeclKind::PatternBinding:
case DeclKind::Var:
case DeclKind::Param:
newBody.push_back(element);
return std::nullopt;
default:
return UnsupportedElt(decl);
}
llvm_unreachable("Unhandled case in switch!");
}
if (auto *stmt = element.dyn_cast<Stmt *>()) {
// Throw is allowed as is.
if (auto *throwStmt = dyn_cast<ThrowStmt>(stmt)) {
newBody.push_back(throwStmt);
return std::nullopt;
}
if (ctx.CompletionCallback && stmt->getSourceRange().isValid() &&
!containsIDEInspectionTarget(stmt->getSourceRange(), ctx.SourceMgr) &&
!isa<GuardStmt>(stmt)) {
// A statement that doesn't contain the code completion expression can't
// influence the type of the code completion expression, so we can skip
// it to improve performance.
return std::nullopt;
}
// Allocate variable with a placeholder type
auto *resultVar = buildPlaceholderVar(stmt->getStartLoc(), newBody);
auto result = visit(stmt, resultVar);
if (!result)
return UnsupportedElt(stmt);
newBody.push_back(result.get());
buildBlockArguments.push_back(
builder.buildVarRef(resultVar, stmt->getStartLoc()));
return std::nullopt;
}
auto *expr = element.get<Expr *>();
if (auto *SVE = dyn_cast<SingleValueStmtExpr>(expr)) {
// This should never be treated as an expression in a result builder, it
// should have statement semantics.
return transformBraceElement(SVE->getStmt(), newBody,
buildBlockArguments);
}
if (builder.supports(ctx.Id_buildExpression)) {
expr = builder.buildCall(expr->getStartLoc(), ctx.Id_buildExpression,
{expr}, {Identifier()});
}
if (isa<CodeCompletionExpr>(expr)) {
// Insert the CodeCompletionExpr directly into the buildBlock call. That
// way, we can extract the contextual type of the code completion token
// to rank code completion items that match the type expected by
// buildBlock higher.
buildBlockArguments.push_back(expr);
} else if (ctx.CompletionCallback && expr->getSourceRange().isValid() &&
containsIDEInspectionTarget(bodyRange, ctx.SourceMgr) &&
!containsIDEInspectionTarget(expr->getSourceRange(),
ctx.SourceMgr)) {
// A top-level expression that doesn't contain the code completion
// expression can't influence the type of the code completion expression
// if they're in the same result builder. Add a variable for it that we
// can put into the buildBlock call but don't add the expression itself
// into the transformed body to improve performance.
auto *resultVar = buildPlaceholderVar(expr->getStartLoc(), newBody);
buildBlockArguments.push_back(
builder.buildVarRef(resultVar, expr->getStartLoc()));
} else {
auto *capture = captureExpr(expr, newBody);
// A reference to the synthesized variable is passed as an argument
// to buildBlock.
buildBlockArguments.push_back(
builder.buildVarRef(capture, element.getStartLoc()));
}
return std::nullopt;
}
std::pair<NullablePtr<Expr>, std::optional<UnsupportedElt>>
transform(BraceStmt *braceStmt, SmallVectorImpl<ASTNode> &newBody) {
SmallVector<Expr *, 4> buildBlockArguments;
auto failTransform = [&](UnsupportedElt unsupported) {
return std::make_pair(nullptr, unsupported);
};
for (auto element : braceStmt->getElements()) {
if (auto unsupported =
transformBraceElement(element, newBody, buildBlockArguments)) {
// When in code completion mode, simply ignore unsported constructs to
// get results for anything that's unrelated to the unsupported
// constructs.
if (!ctx.CompletionCallback) {
return failTransform(*unsupported);
}
}
}
// Synthesize `buildBlock` or `buildPartial` based on captured arguments.
{
// If the builder supports `buildPartialBlock(first:)` and
// `buildPartialBlock(accumulated:next:)`, use this to combine
// sub-expressions pairwise.
if (!buildBlockArguments.empty() && builder.canUseBuildPartialBlock()) {
// let v0 = Builder.buildPartialBlock(first: arg_0)
// let v1 = Builder.buildPartialBlock(accumulated: v0, next: arg_1)
// ...
// let vN = Builder.buildPartialBlock(accumulated: vN-1, next: argN)
auto *buildPartialFirst = builder.buildCall(
braceStmt->getStartLoc(), ctx.Id_buildPartialBlock,
{buildBlockArguments.front()},
/*argLabels=*/{ctx.Id_first});
auto *buildBlockVar = captureExpr(buildPartialFirst, newBody);
for (auto *argExpr : llvm::drop_begin(buildBlockArguments)) {
auto *accumPartialBlock = builder.buildCall(
braceStmt->getStartLoc(), ctx.Id_buildPartialBlock,
{builder.buildVarRef(buildBlockVar, argExpr->getStartLoc()),
argExpr},
{ctx.Id_accumulated, ctx.Id_next});
buildBlockVar = captureExpr(accumPartialBlock, newBody);
}
return std::make_pair(
builder.buildVarRef(buildBlockVar, braceStmt->getStartLoc()),
std::nullopt);
}
// If `buildBlock` does not exist at this point, it could be the case that
// `buildPartialBlock` did not have the sufficient availability for this
// call site. Diagnose it.
else if (!builder.supports(ctx.Id_buildBlock)) {
ctx.Diags.diagnose(
braceStmt->getStartLoc(),
diag::result_builder_missing_available_buildpartialblock,
builder.getType());
return failTransform(braceStmt);
}
// Otherwise, call `buildBlock` on all subexpressions.
// Call Builder.buildBlock(... args ...)
auto *buildBlock = builder.buildCall(
braceStmt->getStartLoc(), ctx.Id_buildBlock, buildBlockArguments,
/*argLabels=*/{});
return std::make_pair(buildBlock, std::nullopt);
}
}
std::pair<bool, UnsupportedElt>
transform(BraceStmt *braceStmt, NullablePtr<VarDecl> bodyVar,
SmallVectorImpl<ASTNode> &elements) {
// Arguments passed to a synthesized `build{Partial}Block`.
SmallVector<Expr *, 4> buildBlockArguments;
auto failure = [&](UnsupportedElt element) {
return std::make_pair(true, element);
};
NullablePtr<Expr> buildBlockVarRef;
std::optional<UnsupportedElt> unsupported;
std::tie(buildBlockVarRef, unsupported) = transform(braceStmt, elements);
if (unsupported)
return failure(*unsupported);
// If this is not a top-level brace statement, we need to form an
// assignment from the `build{Partial}Block` call result variable
// to the provided one.
//
// Use start loc for the return statement so any contextual issues
// are attached to the beginning of the brace instead of its end.
auto resultLoc = braceStmt->getStartLoc();
if (bodyVar) {
elements.push_back(
new (ctx) AssignExpr(builder.buildVarRef(bodyVar.get(), resultLoc),
/*EqualLoc=*/SourceLoc(), buildBlockVarRef.get(),
/*Implicit=*/true));
} else {
Expr *buildBlockResult = buildBlockVarRef.get();
// Otherwise, it's a top-level brace and we need to synthesize
// a call to `buildFialBlock` if supported.
if (builder.supports(ctx.Id_buildFinalResult, {Identifier()})) {
buildBlockResult =
builder.buildCall(resultLoc, ctx.Id_buildFinalResult,
{buildBlockResult}, {Identifier()});
}
elements.push_back(
ReturnStmt::createImplicit(ctx, resultLoc, buildBlockResult));
}
return std::make_pair(false, UnsupportedElt());
}
BraceStmt *cloneBraceWith(BraceStmt *braceStmt,
SmallVectorImpl<ASTNode> &elements) {
auto lBrace = braceStmt ? braceStmt->getLBraceLoc() : SourceLoc();
auto rBrace = braceStmt ? braceStmt->getRBraceLoc() : SourceLoc();
bool implicit = braceStmt ? braceStmt->isImplicit() : true;
return BraceStmt::create(ctx, lBrace, elements, rBrace, implicit);
}
NullablePtr<Stmt> visitBraceStmt(BraceStmt *braceStmt,
NullablePtr<VarDecl> bodyVar) {
SmallVector<ASTNode, 4> elements;
bool failed;
UnsupportedElt unsupported;
std::tie(failed, unsupported) = transform(braceStmt, bodyVar, elements);
if (failed)
return failTransform(unsupported);
return cloneBraceWith(braceStmt, elements);
}
NullablePtr<Stmt> visitDoStmt(DoStmt *doStmt, NullablePtr<VarDecl> doVar) {
auto body = visitBraceStmt(doStmt->getBody(), doVar);
if (!body)
return nullptr;
return new (ctx) DoStmt(doStmt->getLabelInfo(), doStmt->getDoLoc(),
cast<BraceStmt>(body.get()), doStmt->isImplicit());
}
NullablePtr<Stmt> visitIfStmt(IfStmt *ifStmt, NullablePtr<VarDecl> ifVar) {
// Check whether the chain is buildable and whether it terminates
// without an `else`.
bool isOptional = false;
unsigned numPayloads = 0;
if (!isBuildableIfChain(ifStmt, numPayloads, isOptional))
return failTransform(ifStmt);
SmallVector<std::pair<Expr *, Stmt *>, 4> branchVarRefs;
auto transformed = transformIf(ifStmt, branchVarRefs);
if (!transformed)
return failTransform(ifStmt);
// Let's wrap `if` statement into a `do` and inject `type-join`
// operation with appropriate combination of `buildEither` that
// would get re-distributed after inference.
SmallVector<ASTNode, 4> doBody;
{
ifStmt = transformed.get();
// `if` goes first.
doBody.push_back(ifStmt);
assert(numPayloads == branchVarRefs.size());
SmallVector<Expr *, 4> buildEitherCalls;
for (unsigned i = 0; i != numPayloads; i++) {
Expr *branchVarRef;
Stmt *anchor;
std::tie(branchVarRef, anchor) = branchVarRefs[i];
auto *builderCall =
buildWrappedChainPayload(branchVarRef, i, numPayloads, isOptional);
// The operand should have optional type if we had optional results,
// so we just need to call `buildIf` now, since we're at the top level.
if (isOptional) {
builderCall = builder.buildCall(ifStmt->getThenStmt()->getStartLoc(),
builder.getBuildOptionalId(),
builderCall, /*argLabels=*/{});
}
buildEitherCalls.push_back(builderCall);
}
// If there is no `else` branch we need to build one.
// It consists a `buildOptional` call that uses `nil` as an argument.
//
// ```
// {
// $__builderResult = buildOptional(nil)
// }
// ```
//
// Type of `nil` is going to be inferred from `$__builderResult`.
if (!hasUnconditionalElse(ifStmt)) {
assert(isOptional);
auto *nil =
new (ctx) NilLiteralExpr(ifStmt->getEndLoc(), /*implicit=*/true);
buildEitherCalls.push_back(builder.buildCall(
/*loc=*/ifStmt->getEndLoc(), builder.getBuildOptionalId(), nil,
/*argLabels=*/{}));
}
auto *ifVarRef = builder.buildVarRef(ifVar.get(), ifStmt->getStartLoc());
doBody.push_back(TypeJoinExpr::create(ctx, ifVarRef, buildEitherCalls));
}
return DoStmt::createImplicit(ctx, LabeledStmtInfo(), doBody);
}
NullablePtr<IfStmt>
transformIf(IfStmt *ifStmt,
SmallVectorImpl<std::pair<Expr *, Stmt *>> &branchVarRefs) {
std::optional<UnsupportedElt> unsupported;
// If there is a #available in the condition, wrap the 'then' or 'else'
// in a call to buildLimitedAvailability(_:).
auto availabilityCond = findAvailabilityCondition(ifStmt->getCond());
bool supportsAvailability =
availabilityCond && builder.supports(ctx.Id_buildLimitedAvailability);
NullablePtr<Expr> thenVarRef;
NullablePtr<BraceStmt> thenBranch;
{
SmallVector<ASTNode, 4> thenBody;
auto *ifBraceStmt = cast<BraceStmt>(ifStmt->getThenStmt());
std::tie(thenVarRef, unsupported) = transform(ifBraceStmt, thenBody);
if (unsupported) {
recordUnsupported(*unsupported);
return nullptr;
}
if (supportsAvailability &&
!availabilityCond->getAvailability()->isUnavailability()) {
auto *builderCall = builder.buildCall(
ifBraceStmt->getStartLoc(), ctx.Id_buildLimitedAvailability,
{thenVarRef.get()}, {Identifier()});
thenVarRef = builder.buildVarRef(captureExpr(builderCall, thenBody),
ifBraceStmt->getStartLoc());
}
thenBranch = cloneBraceWith(ifBraceStmt, thenBody);
branchVarRefs.push_back({thenVarRef.get(), thenBranch.get()});
}
NullablePtr<Stmt> elseBranch;
if (auto *elseStmt = ifStmt->getElseStmt()) {
NullablePtr<Expr> elseVarRef;
if (auto *innerIfStmt = getAsStmt<IfStmt>(elseStmt)) {
elseBranch = transformIf(innerIfStmt, branchVarRefs);
if (!elseBranch) {
recordUnsupported(innerIfStmt);
return nullptr;
}
} else {
auto *elseBraceStmt = cast<BraceStmt>(elseStmt);
SmallVector<ASTNode> elseBody;
std::tie(elseVarRef, unsupported) = transform(elseBraceStmt, elseBody);
if (unsupported) {
recordUnsupported(*unsupported);
return nullptr;
}
// If there is a #unavailable in the condition, wrap the 'else' in a
// call to buildLimitedAvailability(_:).
if (supportsAvailability &&
availabilityCond->getAvailability()->isUnavailability()) {
auto *builderCall = builder.buildCall(
elseBraceStmt->getStartLoc(), ctx.Id_buildLimitedAvailability,
{elseVarRef.get()}, {Identifier()});
elseVarRef = builder.buildVarRef(captureExpr(builderCall, elseBody),
elseBraceStmt->getStartLoc());
}
elseBranch = cloneBraceWith(elseBraceStmt, elseBody);
branchVarRefs.push_back({elseVarRef.get(), elseBranch.get()});
}
}
return new (ctx)
IfStmt(ifStmt->getLabelInfo(), ifStmt->getIfLoc(), ifStmt->getCond(),
thenBranch.get(), ifStmt->getElseLoc(),
elseBranch.getPtrOrNull(), ifStmt->isImplicit());
}
NullablePtr<Stmt> visitSwitchStmt(SwitchStmt *switchStmt,
NullablePtr<VarDecl> switchVar) {
// For a do statement wrapping this switch that contains all of the
// `buildEither` calls that would get injected back into `case` bodies
// after solving is done.
//
// This is necessary because `buildEither requires type information from
// both sides to be available, so all case statements have to be
// type-checked first.
SmallVector<ASTNode, 4> doBody;
SmallVector<ASTNode, 4> cases;
SmallVector<Expr *, 4> caseVarRefs;
for (auto *caseStmt : switchStmt->getCases()) {
auto transformed = transformCase(caseStmt);
if (!transformed)
return failTransform(caseStmt);
cases.push_back(transformed->second);
caseVarRefs.push_back(transformed->first);
}
// If there are no 'case' statements in the body let's try
// to diagnose this situation via limited exhaustiveness check
// before failing a builder transform, otherwise type-checker
// might end up without any diagnostics which leads to crashes
// in SILGen.
if (caseVarRefs.empty()) {
TypeChecker::checkSwitchExhaustiveness(switchStmt, dc,
/*limitChecking=*/true);
return failTransform(switchStmt);
}
auto *transformedSwitch = SwitchStmt::create(
switchStmt->getLabelInfo(), switchStmt->getSwitchLoc(),
switchStmt->getSubjectExpr(), switchStmt->getLBraceLoc(), cases,
switchStmt->getRBraceLoc(), switchStmt->getEndLoc(), ctx);
doBody.push_back(transformedSwitch);
SmallVector<Expr *, 4> injectedExprs;
for (auto idx : indices(caseVarRefs)) {
auto *caseVarRef = caseVarRefs[idx];
// Build the expression that injects the case variable into appropriate
// buildEither(first:)/buildEither(second:) chain.
Expr *injectedCaseExpr = buildWrappedChainPayload(
caseVarRef, idx, caseVarRefs.size(), /*isOptional=*/false);
injectedExprs.push_back(injectedCaseExpr);
}
auto *switchVarRef =
builder.buildVarRef(switchVar.get(), switchStmt->getEndLoc());
doBody.push_back(TypeJoinExpr::create(ctx, switchVarRef, injectedExprs));
return DoStmt::createImplicit(ctx, LabeledStmtInfo(), doBody);
}
std::optional<std::pair<Expr *, CaseStmt *>>
transformCase(CaseStmt *caseStmt) {
auto *body = caseStmt->getBody();
// Explicitly disallow `case` statements with empty bodies
// since that helps to diagnose other issues with switch
// statements by excluding invalid cases.
if (auto *BS = dyn_cast<BraceStmt>(body)) {
if (BS->getNumElements() == 0) {
// HACK: still allow empty bodies if typechecking for code
// completion. Code completion ignores diagnostics
// and won't get any types if we fail.
if (!ctx.SourceMgr.hasIDEInspectionTargetBuffer())
return std::nullopt;
}
}
NullablePtr<Expr> caseVarRef;
std::optional<UnsupportedElt> unsupported;
SmallVector<ASTNode, 4> newBody;
std::tie(caseVarRef, unsupported) = transform(body, newBody);
if (unsupported) {
recordUnsupported(*unsupported);
return std::nullopt;
}
auto *newCase = CaseStmt::create(
ctx, caseStmt->getParentKind(), caseStmt->getLoc(),
caseStmt->getCaseLabelItems(),
caseStmt->hasUnknownAttr() ? caseStmt->getStartLoc() : SourceLoc(),
caseStmt->getItemTerminatorLoc(), cloneBraceWith(body, newBody),
caseStmt->getCaseBodyVariablesOrEmptyArray(), caseStmt->isImplicit(),
caseStmt->getFallthroughStmt());
return std::make_pair(caseVarRef.get(), newCase);
}
/// do {
/// var $__forEach = []
/// for ... in ... {
/// ...
/// $__builderVar = buildBlock(...)
/// $__forEach.append($__builderVar)
/// }
/// buildArray($__forEach)
/// }
NullablePtr<Stmt> visitForEachStmt(ForEachStmt *forEachStmt,
NullablePtr<VarDecl> forEachVar) {
// for...in statements are handled via buildArray(_:); bail out if the
// builder does not support it.
if (!builder.supports(ctx.Id_buildArray))
return failTransform(forEachStmt);
// For-each statements require the Sequence protocol. If we don't have
// it (which generally means the standard library isn't loaded), fall
// out of the result-builder path entirely to let normal type checking
// take care of this.
auto sequenceProto = TypeChecker::getProtocol(
dc->getASTContext(), forEachStmt->getForLoc(),
forEachStmt->getAwaitLoc().isValid() ? KnownProtocolKind::AsyncSequence
: KnownProtocolKind::Sequence);
if (!sequenceProto)
return failTransform(forEachStmt);
SmallVector<ASTNode, 4> doBody;
SourceLoc endLoc = forEachStmt->getEndLoc();
// Build a variable that is going to hold array of results produced
// by each iteration of the loop.
//
// Not that it's not going to be initialized here, that would happen
// only when a solution is found.
VarDecl *arrayVar = buildPlaceholderVar(
forEachStmt->getEndLoc(), doBody,
ArraySliceType::get(PlaceholderType::get(ctx, forEachVar.get())),
ArrayExpr::create(ctx, /*LBrace=*/endLoc, /*Elements=*/{},
/*Commas=*/{}, /*RBrace=*/endLoc));
NullablePtr<Expr> bodyVarRef;
std::optional<UnsupportedElt> unsupported;
SmallVector<ASTNode, 4> newBody;
{
std::tie(bodyVarRef, unsupported) =
transform(forEachStmt->getBody(), newBody);
if (unsupported)
return failTransform(*unsupported);
// Form a call to Array.append(_:) to add the result of executing each
// iteration of the loop body to the array formed above.
{
auto arrayVarRef = builder.buildVarRef(arrayVar, endLoc);
auto arrayAppendRef = new (ctx) UnresolvedDotExpr(
arrayVarRef, endLoc, DeclNameRef(ctx.getIdentifier("append")),
DeclNameLoc(endLoc), /*implicit=*/true);
arrayAppendRef->setFunctionRefKind(FunctionRefKind::SingleApply);
auto *argList = ArgumentList::createImplicit(
ctx, endLoc, {Argument::unlabeled(bodyVarRef.get())}, endLoc);
newBody.push_back(
CallExpr::createImplicit(ctx, arrayAppendRef, argList));
}
}
auto *newForEach = new (ctx)
ForEachStmt(forEachStmt->getLabelInfo(), forEachStmt->getForLoc(),
forEachStmt->getTryLoc(), forEachStmt->getAwaitLoc(),
forEachStmt->getPattern(), forEachStmt->getInLoc(),
forEachStmt->getParsedSequence(),
forEachStmt->getWhereLoc(), forEachStmt->getWhere(),
cloneBraceWith(forEachStmt->getBody(), newBody),
forEachStmt->isImplicit());
// For a body of new `do` statement that holds updated `for-in` loop
// and epilog that consists of a call to `buildArray` that forms the
// final result.
{
// Modified `for { ... }`
doBody.push_back(newForEach);
// $__forEach = buildArray($__arrayVar)
doBody.push_back(buildAssignment(
forEachVar.get(),
builder.buildCall(forEachStmt->getEndLoc(), ctx.Id_buildArray,
{builder.buildVarRef(arrayVar, endLoc)},
{Identifier()})));
}
return DoStmt::createImplicit(ctx, LabeledStmtInfo(), doBody);
}
UNSUPPORTED_STMT(Throw)
UNSUPPORTED_STMT(Return)
UNSUPPORTED_STMT(Yield)
UNSUPPORTED_STMT(Then)
UNSUPPORTED_STMT(Discard)
UNSUPPORTED_STMT(Defer)
UNSUPPORTED_STMT(Guard)
UNSUPPORTED_STMT(While)
UNSUPPORTED_STMT(DoCatch)
UNSUPPORTED_STMT(RepeatWhile)
UNSUPPORTED_STMT(Break)
UNSUPPORTED_STMT(Continue)
UNSUPPORTED_STMT(Fallthrough)
UNSUPPORTED_STMT(Fail)
UNSUPPORTED_STMT(PoundAssert)
UNSUPPORTED_STMT(Case)
#undef UNSUPPORTED_STMT
private:
static bool isBuildableIfChainRecursive(IfStmt *ifStmt, unsigned &numPayloads,
bool &isOptional) {
// The 'then' clause contributes a payload.
++numPayloads;
// If there's an 'else' clause, it contributes payloads:
if (auto elseStmt = ifStmt->getElseStmt()) {
// If it's 'else if', it contributes payloads recursively.
if (auto elseIfStmt = dyn_cast<IfStmt>(elseStmt)) {
return isBuildableIfChainRecursive(elseIfStmt, numPayloads, isOptional);
// Otherwise it's just the one.
} else {
++numPayloads;
}
// If not, the chain result is at least optional.
} else {
isOptional = true;
}
return true;
}
static bool hasUnconditionalElse(IfStmt *ifStmt) {
if (auto *elseStmt = ifStmt->getElseStmt()) {
if (auto *ifStmt = dyn_cast<IfStmt>(elseStmt))
return hasUnconditionalElse(ifStmt);
return true;
}
return false;
}
bool isBuildableIfChain(IfStmt *ifStmt, unsigned &numPayloads,
bool &isOptional) {
if (!isBuildableIfChainRecursive(ifStmt, numPayloads, isOptional))
return false;
// If there's a missing 'else', we need 'buildOptional' to exist.
if (isOptional && !builder.supportsOptional())
return false;
// If there are multiple clauses, we need 'buildEither(first:)' and
// 'buildEither(second:)' to both exist.
if (numPayloads > 1) {
if (!builder.supports(ctx.Id_buildEither, {ctx.Id_first}) ||
!builder.supports(ctx.Id_buildEither, {ctx.Id_second}))
return false;
}
return true;
}
/// Wrap a payload value in an expression which will produce a chain
/// result (without `buildIf`).
Expr *buildWrappedChainPayload(Expr *operand, unsigned payloadIndex,
unsigned numPayloads, bool isOptional) {
assert(payloadIndex < numPayloads);
// Inject into the appropriate chain position.
//
// We produce a (left-biased) balanced binary tree of Eithers in order
// to prevent requiring a linear number of injections in the worst case.
// That is, if we have 13 clauses, we want to produce:
//
// /------------------Either------------\
// /-------Either-------\ /--Either--\
// /--Either--\ /--Either--\ /--Either--\ \
// /-E-\ /-E-\ /-E-\ /-E-\ /-E-\ /-E-\ \
// 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100
//
// Note that a prefix of length D of the payload index acts as a path
// through the tree to the node at depth D. On the rightmost path
// through the tree (when this prefix is equal to the corresponding
// prefix of the maximum payload index), the bits of the index mark
// where Eithers are required.
//
// Since we naturally want to build from the innermost Either out, and
// therefore work with progressively shorter prefixes, we can do it all
// with right-shifts.
for (auto path = payloadIndex, maxPath = numPayloads - 1; maxPath != 0;
path >>= 1, maxPath >>= 1) {
// Skip making Eithers on the rightmost path where they aren't required.
// This isn't just an optimization: adding spurious Eithers could
// leave us with unresolvable type variables if `buildEither` has
// a signature like:
// static func buildEither<T,U>(first value: T) -> Either<T,U>
// which relies on unification to work.
if (path == maxPath && !(maxPath & 1))
continue;
bool isSecond = (path & 1);
operand =
builder.buildCall(operand->getStartLoc(), ctx.Id_buildEither, operand,
{isSecond ? ctx.Id_second : ctx.Id_first});
}
// Inject into Optional if required. We'll be adding the call to
// `buildIf` after all the recursive calls are complete.
if (isOptional) {
operand = buildSomeExpr(operand);
}
return operand;
}
Expr *buildSomeExpr(Expr *arg) {
auto optionalDecl = ctx.getOptionalDecl();
auto optionalType = optionalDecl->getDeclaredType();
auto loc = arg->getStartLoc();
auto optionalTypeExpr =
TypeExpr::createImplicitHack(loc, optionalType, ctx);
auto someRef = new (ctx) UnresolvedDotExpr(
optionalTypeExpr, loc, DeclNameRef(ctx.getIdentifier("some")),
DeclNameLoc(loc), /*implicit=*/true);
auto *argList = ArgumentList::forImplicitUnlabeled(ctx, {arg});
return CallExpr::createImplicit(ctx, someRef, argList);
}
Expr *buildNoneExpr(SourceLoc endLoc) {
auto optionalDecl = ctx.getOptionalDecl();
auto optionalType = optionalDecl->getDeclaredType();
auto optionalTypeExpr =
TypeExpr::createImplicitHack(endLoc, optionalType, ctx);
return new (ctx) UnresolvedDotExpr(optionalTypeExpr, endLoc,
DeclNameRef(ctx.getIdentifier("none")),
DeclNameLoc(endLoc), /*implicit=*/true);
}
};
} // end anonymous namespace
std::optional<BraceStmt *>
TypeChecker::applyResultBuilderBodyTransform(FuncDecl *func, Type builderType) {
// Pre-check the body: pre-check any expressions in it and look
// for return statements.
//
// If we encountered an error or there was an explicit result type,
// bail out and report that to the caller.
auto &ctx = func->getASTContext();
auto request =
PreCheckResultBuilderRequest{{AnyFunctionRef(func),
/*SuppressDiagnostics=*/false}};
switch (evaluateOrDefault(ctx.evaluator, request,
ResultBuilderBodyPreCheck::Error)) {
case ResultBuilderBodyPreCheck::Okay:
// If the pre-check was okay, apply the result-builder transform.
break;
case ResultBuilderBodyPreCheck::Error:
return nullptr;
case ResultBuilderBodyPreCheck::HasReturnStmt: {
// One or more explicit 'return' statements were encountered, which
// disables the result builder transform. Warn when we do this.
auto returnStmts = findReturnStatements(func);
assert(!returnStmts.empty());
ctx.Diags.diagnose(
returnStmts.front()->getReturnLoc(),
diag::result_builder_disabled_by_return_warn, builderType);
// Note that one can remove the result builder attribute.
auto attr = func->getAttachedResultBuilder();
if (!attr) {
if (auto accessor = dyn_cast<AccessorDecl>(func)) {
attr = accessor->getStorage()->getAttachedResultBuilder();
}
}
if (attr) {
diagnoseAndRemoveAttr(func, attr, diag::result_builder_remove_attr);
}
// Note that one can remove all of the return statements.
{
auto diag = ctx.Diags.diagnose(
returnStmts.front()->getReturnLoc(),
diag::result_builder_remove_returns);
for (auto returnStmt : returnStmts) {
diag.fixItRemove(returnStmt->getReturnLoc());
}
}
return std::nullopt;
}
}
ConstraintSystemOptions options = ConstraintSystemFlags::AllowFixes;
auto resultInterfaceTy = func->getResultInterfaceType();
auto resultContextType = func->mapTypeIntoContext(resultInterfaceTy);
// Determine whether we're inferring the underlying type for the opaque
// result type of this function.
ConstraintKind resultConstraintKind = ConstraintKind::Conversion;
if (auto opaque = resultContextType->getAs<OpaqueTypeArchetypeType>()) {
if (opaque->getDecl()->isOpaqueReturnTypeOfFunction(func)) {
resultConstraintKind = ConstraintKind::Equal;
}
}
// Build a constraint system in which we can check the body of the function.
ConstraintSystem cs(func, options);
if (cs.isDebugMode()) {
auto &log = llvm::errs();
log << "--- Applying result builder to function ---\n";
func->dump(log);
log << '\n';
}
// Map type parameters into context. We don't want type
// parameters to appear in the result builder type, because
// the result builder type will only be used inside the body
// of this decl; it's not part of the interface type.
builderType = func->mapTypeIntoContext(builderType);
if (auto result = cs.matchResultBuilder(
func, builderType, resultContextType, resultConstraintKind,
/*contextualType=*/Type(),
cs.getConstraintLocator(func->getBody()))) {
if (result->isFailure())
return nullptr;
}
// Solve the constraint system.
if (cs.getASTContext().CompletionCallback) {
SmallVector<Solution, 4> solutions;
cs.Options |= ConstraintSystemFlags::AllowFixes;
cs.Options |= ConstraintSystemFlags::SuppressDiagnostics;
cs.Options |= ConstraintSystemFlags::ForCodeCompletion;
cs.solveForCodeCompletion(solutions);
SyntacticElementTarget funcTarget(func);
CompletionContextFinder analyzer(funcTarget, func->getDeclContext());
if (analyzer.hasCompletion()) {
filterSolutionsForCodeCompletion(solutions, analyzer);
for (const auto &solution : solutions) {
cs.getASTContext().CompletionCallback->sawSolution(solution);
}
}
return nullptr;
}
SmallVector<Solution, 4> solutions;
bool solvingFailed = cs.solve(solutions);
auto reportSolutionsToSolutionCallback = [&](const SolutionResult &result) {
if (!cs.getASTContext().SolutionCallback) {
return;
}
switch (result.getKind()) {
case SolutionResult::Success:
cs.getASTContext().SolutionCallback->sawSolution(result.getSolution());
break;
case SolutionResult::Ambiguous:
for (auto &solution : result.getAmbiguousSolutions()) {
cs.getASTContext().SolutionCallback->sawSolution(solution);
}
break;
default:
break;
}
};
if (solvingFailed || solutions.size() != 1) {
// Try to fix the system or provide a decent diagnostic.
auto salvagedResult = cs.salvage();
switch (salvagedResult.getKind()) {
case SolutionResult::Kind::Success:
solutions.clear();
solutions.push_back(std::move(salvagedResult).takeSolution());
break;
case SolutionResult::Kind::Error:
case SolutionResult::Kind::Ambiguous:
reportSolutionsToSolutionCallback(salvagedResult);
return nullptr;
case SolutionResult::Kind::UndiagnosedError:
reportSolutionsToSolutionCallback(salvagedResult);
cs.diagnoseFailureFor(SyntacticElementTarget(func));
salvagedResult.markAsDiagnosed();
return nullptr;
case SolutionResult::Kind::TooComplex:
reportSolutionsToSolutionCallback(salvagedResult);
func->diagnose(diag::expression_too_complex)
.highlight(func->getBodySourceRange());
salvagedResult.markAsDiagnosed();
return nullptr;
}
// The system was salvaged; continue on as if nothing happened.
}
if (cs.isDebugMode()) {
auto indent = cs.solverState ? cs.solverState->getCurrentIndent() : 0;
auto &log = llvm::errs().indent(indent);
log << "--- Applying Solution ---\n";
solutions.front().dump(log, indent);
log << '\n';
}
if (cs.getASTContext().SolutionCallback) {
for (auto &solution : solutions) {
cs.getASTContext().SolutionCallback->sawSolution(solution);
}
return nullptr;
}
// FIXME: Shouldn't need to do this.
cs.applySolution(solutions.front());
// Apply the solution to the function body.
if (auto result =
cs.applySolution(solutions.front(), SyntacticElementTarget(func))) {
performSyntacticDiagnosticsForTarget(*result, /*isExprStmt*/ false);
auto *body = result->getFunctionBody();
if (cs.isDebugMode()) {
auto indent = cs.solverState ? cs.solverState->getCurrentIndent() : 0;
auto &log = llvm::errs().indent(indent);
log << "--- Type-checked function body ---\n";
body->dump(log);
log << '\n';
}
return body;
}
return nullptr;
}
std::optional<ConstraintSystem::TypeMatchResult>
ConstraintSystem::matchResultBuilder(AnyFunctionRef fn, Type builderType,
Type bodyResultType,
ConstraintKind bodyResultConstraintKind,
Type contextualType,
ConstraintLocatorBuilder locator) {
builderType = simplifyType(builderType);
auto builder = builderType->getAnyNominal();
assert(builder && "Bad result builder type");
assert(builder->getAttrs().hasAttribute<ResultBuilderAttr>());
assert(!builderType->hasTypeParameter());
if (InvalidResultBuilderBodies.count(fn)) {
(void)recordFix(IgnoreInvalidResultBuilderBody::create(
*this, getConstraintLocator(fn.getAbstractClosureExpr())));
return getTypeMatchSuccess();
}
// We have already pre-checked the result builder body. Technically, we
// shouldn't need to do anything here, but there was a bug here that we did
// not apply the result builder transform if it contained an explicit return.
// To maintain source compatibility, we still need to check for HasReturnStmt.
// https://github.com/apple/swift/issues/64332.
auto request =
PreCheckResultBuilderRequest{{fn, /*SuppressDiagnostics=*/false}};
switch (evaluateOrDefault(getASTContext().evaluator, request,
ResultBuilderBodyPreCheck::Error)) {
case ResultBuilderBodyPreCheck::Okay:
// If the pre-check was okay, apply the result-builder transform.
break;
case ResultBuilderBodyPreCheck::Error: {
llvm_unreachable(
"Running PreCheckResultBuilderRequest on a function shouldn't run "
"preCheckExpression and thus we should never enter this case.");
break;
}
case ResultBuilderBodyPreCheck::HasReturnStmt:
// Diagnostic mode means that solver couldn't reach any viable
// solution, so let's diagnose presence of a `return` statement
// in the closure body.
if (shouldAttemptFixes()) {
if (recordFix(IgnoreResultBuilderWithReturnStmts::create(
*this, builderType,
getConstraintLocator(fn.getAbstractClosureExpr()))))
return getTypeMatchFailure(locator);
return getTypeMatchSuccess();
}
// If the body has a return statement, suppress the transform but
// continue solving the constraint system.
return std::nullopt;
}
auto transformedBody = getBuilderTransformedBody(fn, builder);
// If this builder transform has not yet been applied to this function,
// let's do it and cache the result.
if (!transformedBody) {
ResultBuilderTransform transform(*this, fn.getAsDeclContext(),
fn.getBody()->getSourceRange(),
builderType, bodyResultType);
auto *body = transform.apply(fn.getBody());
if (auto unsupported = transform.getUnsupportedElement()) {
assert(!body || getASTContext().CompletionCallback);
// If we aren't supposed to attempt fixes, fail.
if (!shouldAttemptFixes()) {
return getTypeMatchFailure(locator);
}
// If we're solving for code completion and the body contains the code
// completion location, skipping it won't get us to a useful solution so
// just bail.
if (isForCodeCompletion() &&
containsIDEInspectionTarget(fn.getBody())) {
return getTypeMatchFailure(locator);
}
// Record the first unhandled construct as a fix.
if (recordFix(
SkipUnhandledConstructInResultBuilder::create(
*this, unsupported, builder, getConstraintLocator(locator)),
/*impact=*/100)) {
return getTypeMatchFailure(locator);
}
if (auto *closure =
getAsExpr<ClosureExpr>(fn.getAbstractClosureExpr())) {
recordTypeVariablesAsHoles(getClosureType(closure));
}
return getTypeMatchSuccess();
}
transformedBody = std::make_pair(transform.getBuilderSelf(), body);
// Record the transformation so it could be re-used if needed.
setBuilderTransformedBody(fn, builder, transformedBody->first,
transformedBody->second);
}
// Set the type of `$__builderSelf` variable before constraint generation.
setType(transformedBody->first, MetatypeType::get(builderType));
if (isDebugMode()) {
auto &log = llvm::errs();
auto indent = solverState ? solverState->getCurrentIndent() : 0;
log.indent(indent) << "------- Transformed Body -------\n";
transformedBody->second->dump(log, &getASTContext(), indent);
log << '\n';
}
AppliedBuilderTransform transformInfo;
transformInfo.builderType = builderType;
transformInfo.bodyResultType = bodyResultType;
transformInfo.contextualType = contextualType;
transformInfo.transformedBody = transformedBody->second;
// Record the transformation.
assert(
std::find_if(
resultBuilderTransformed.begin(), resultBuilderTransformed.end(),
[&](const std::pair<AnyFunctionRef, AppliedBuilderTransform> &elt) {
return elt.first == fn;
}) == resultBuilderTransformed.end() &&
"already transformed this body along this path!?!");
resultBuilderTransformed.insert(
std::make_pair(fn, std::move(transformInfo)));
if (generateConstraints(fn, transformInfo.transformedBody))
return getTypeMatchFailure(locator);
return getTypeMatchSuccess();
}
namespace {
/// Pre-check all the expressions in the body.
class PreCheckResultBuilderApplication : public ASTWalker {
AnyFunctionRef Fn;
bool SkipPrecheck = false;
bool SuppressDiagnostics = false;
std::vector<ReturnStmt *> ReturnStmts;
bool HasError = false;
bool hasReturnStmt() const { return !ReturnStmts.empty(); }
public:
PreCheckResultBuilderApplication(AnyFunctionRef fn, bool skipPrecheck,
bool suppressDiagnostics)
: Fn(fn), SkipPrecheck(skipPrecheck),
SuppressDiagnostics(suppressDiagnostics) {}
const std::vector<ReturnStmt *> getReturnStmts() const { return ReturnStmts; }
ResultBuilderBodyPreCheck run() {
Stmt *oldBody = Fn.getBody();
Stmt *newBody = oldBody->walk(*this);
// If the walk was aborted, it was because we had a problem of some kind.
assert((newBody == nullptr) == HasError &&
"unexpected short-circuit while walking body");
if (HasError)
return ResultBuilderBodyPreCheck::Error;
assert(oldBody == newBody && "pre-check walk wasn't in-place?");
if (hasReturnStmt())
return ResultBuilderBodyPreCheck::HasReturnStmt;
return ResultBuilderBodyPreCheck::Okay;
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::Arguments;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
if (SkipPrecheck)
return Action::SkipNode(E);
// Pre-check the expression. If this fails, abort the walk immediately.
// Otherwise, replace the expression with the result of pre-checking.
// In either case, don't recurse into the expression.
{
auto *DC = Fn.getAsDeclContext();
auto &diagEngine = DC->getASTContext().Diags;
// Suppress any diagnostics which could be produced by this expression.
DiagnosticTransaction transaction(diagEngine);
HasError |= ConstraintSystem::preCheckExpression(
E, DC, /*replaceInvalidRefsWithErrors=*/true);
HasError |= transaction.hasErrors();
if (!HasError)
HasError |= containsErrorExpr(E);
if (SuppressDiagnostics)
transaction.abort();
if (HasError)
return Action::Stop();
return Action::SkipNode(E);
}
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
// If we see a return statement, note it..
if (auto returnStmt = dyn_cast<ReturnStmt>(S)) {
if (!returnStmt->isImplicit()) {
ReturnStmts.push_back(returnStmt);
return Action::SkipNode(S);
}
}
// Otherwise, recurse into the statement normally.
return Action::Continue(S);
}
/// Check whether given expression (including single-statement
/// closures) contains `ErrorExpr` as one of its sub-expressions.
bool containsErrorExpr(Expr *expr) {
bool hasError = false;
expr->forEachChildExpr([&](Expr *expr) -> Expr * {
hasError |= isa<ErrorExpr>(expr);
if (hasError)
return nullptr;
if (auto *closure = dyn_cast<ClosureExpr>(expr)) {
if (closure->hasSingleExpressionBody()) {
hasError |= containsErrorExpr(closure->getSingleExpressionBody());
return hasError ? nullptr : expr;
}
}
return expr;
});
return hasError;
}
/// Ignore patterns.
PreWalkResult<Pattern *> walkToPatternPre(Pattern *pat) override {
return Action::SkipNode(pat);
}
};
}
ResultBuilderBodyPreCheck PreCheckResultBuilderRequest::evaluate(
Evaluator &evaluator, PreCheckResultBuilderDescriptor owner) const {
// Closures should already be pre-checked when we run this, so there's no need
// to pre-check them again.
bool skipPrecheck = owner.Fn.getAbstractClosureExpr();
return PreCheckResultBuilderApplication(
owner.Fn, skipPrecheck,
/*suppressDiagnostics=*/owner.SuppressDiagnostics)
.run();
}
std::vector<ReturnStmt *> TypeChecker::findReturnStatements(AnyFunctionRef fn) {
PreCheckResultBuilderApplication precheck(fn, /*skipPreCheck=*/true,
/*SuppressDiagnostics=*/true);
(void)precheck.run();
return precheck.getReturnStmts();
}
ResultBuilderOpSupport TypeChecker::checkBuilderOpSupport(
Type builderType, DeclContext *dc, Identifier fnName,
ArrayRef<Identifier> argLabels, SmallVectorImpl<ValueDecl *> *allResults) {
auto isUnavailable = [&](Decl *D) -> bool {
if (AvailableAttr::isUnavailable(D))
return true;
auto loc = extractNearestSourceLoc(dc);
auto context = ExportContext::forFunctionBody(dc, loc);
return TypeChecker::checkDeclarationAvailability(D, context).has_value();
};
bool foundMatch = false;
bool foundUnavailable = false;
SmallVector<ValueDecl *, 4> foundDecls;
dc->lookupQualified(
builderType, DeclNameRef(fnName),
builderType->getAnyNominal()->getLoc(),
NL_QualifiedDefault | NL_ProtocolMembers, foundDecls);
for (auto decl : foundDecls) {
if (auto func = dyn_cast<FuncDecl>(decl)) {
// Function must be static.
if (!func->isStatic())
continue;
// Function must have the right argument labels, if provided.
if (!argLabels.empty()) {
auto funcLabels = func->getName().getArgumentNames();
if (argLabels.size() > funcLabels.size() ||
funcLabels.slice(0, argLabels.size()) != argLabels)
continue;
}
// Check if the candidate has a suitable availability for the
// calling context.
if (isUnavailable(func)) {
foundUnavailable = true;
continue;
}
foundMatch = true;
break;
}
}
if (allResults)
allResults->append(foundDecls.begin(), foundDecls.end());
if (!foundMatch) {
return foundUnavailable ? ResultBuilderOpSupport::Unavailable
: ResultBuilderOpSupport::Unsupported;
}
// If the builder type itself isn't available, don't consider any builder
// method available.
if (auto *D = builderType->getAnyNominal()) {
if (isUnavailable(D))
return ResultBuilderOpSupport::Unavailable;
}
return ResultBuilderOpSupport::Supported;
}
bool TypeChecker::typeSupportsBuilderOp(
Type builderType, DeclContext *dc, Identifier fnName,
ArrayRef<Identifier> argLabels, SmallVectorImpl<ValueDecl *> *allResults) {
return checkBuilderOpSupport(builderType, dc, fnName, argLabels, allResults)
.isSupported(/*requireAvailable*/ false);
}
Type swift::inferResultBuilderComponentType(NominalTypeDecl *builder) {
Type componentType;
SmallVector<ValueDecl *, 4> potentialMatches;
ASTContext &ctx = builder->getASTContext();
bool supportsBuildBlock = TypeChecker::typeSupportsBuilderOp(
builder->getDeclaredInterfaceType(), builder, ctx.Id_buildBlock,
/*argLabels=*/{}, &potentialMatches);
if (supportsBuildBlock) {
for (auto decl : potentialMatches) {
auto func = dyn_cast<FuncDecl>(decl);
if (!func || !func->isStatic())
continue;
// If we haven't seen a component type before, gather it.
if (!componentType) {
componentType = func->getResultInterfaceType();
continue;
}
// If there are inconsistent component types, bail out.
if (!componentType->isEqual(func->getResultInterfaceType())) {
componentType = Type();
break;
}
}
}
return componentType;
}
std::tuple<SourceLoc, std::string, Type>
swift::determineResultBuilderBuildFixItInfo(NominalTypeDecl *builder) {
SourceLoc buildInsertionLoc = builder->getBraces().Start;
std::string stubIndent;
Type componentType;
if (buildInsertionLoc.isInvalid())
return std::make_tuple(buildInsertionLoc, stubIndent, componentType);
ASTContext &ctx = builder->getASTContext();
buildInsertionLoc = Lexer::getLocForEndOfToken(
ctx.SourceMgr, buildInsertionLoc);
StringRef extraIndent;
StringRef currentIndent = Lexer::getIndentationForLine(
ctx.SourceMgr, buildInsertionLoc, &extraIndent);
stubIndent = (currentIndent + extraIndent).str();
componentType = inferResultBuilderComponentType(builder);
return std::make_tuple(buildInsertionLoc, stubIndent, componentType);
}
void swift::printResultBuilderBuildFunction(
NominalTypeDecl *builder, Type componentType,
ResultBuilderBuildFunction function, std::optional<std::string> stubIndent,
llvm::raw_ostream &out) {
// Render the component type into a string.
std::string componentTypeString;
if (componentType)
componentTypeString = componentType.getString();
else
componentTypeString = "<#Component#>";
// Render the code.
std::string stubIndentStr = stubIndent.value_or(std::string());
ExtraIndentStreamPrinter printer(out, stubIndentStr);
// If we're supposed to provide a full stub, add a newline and the introducer
// keywords.
if (stubIndent) {
printer.printNewline();
if (builder->getFormalAccess() >= AccessLevel::Public)
printer << "public ";
printer << "static func ";
}
bool printedResult = false;
switch (function) {
case ResultBuilderBuildFunction::BuildBlock:
printer << "buildBlock(_ components: " << componentTypeString << "...)";
break;
case ResultBuilderBuildFunction::BuildExpression:
printer << "buildExpression(_ expression: <#Expression#>)";
break;
case ResultBuilderBuildFunction::BuildOptional:
printer << "buildOptional(_ component: " << componentTypeString << "?)";
break;
case ResultBuilderBuildFunction::BuildEitherFirst:
printer << "buildEither(first component: " << componentTypeString << ")";
break;
case ResultBuilderBuildFunction::BuildEitherSecond:
printer << "buildEither(second component: " << componentTypeString << ")";
break;
case ResultBuilderBuildFunction::BuildArray:
printer << "buildArray(_ components: [" << componentTypeString << "])";
break;
case ResultBuilderBuildFunction::BuildLimitedAvailability:
printer << "buildLimitedAvailability(_ component: " << componentTypeString
<< ")";
break;
case ResultBuilderBuildFunction::BuildFinalResult:
printer << "buildFinalResult(_ component: " << componentTypeString
<< ") -> <#Result#>";
printedResult = true;
break;
case ResultBuilderBuildFunction::BuildPartialBlockFirst:
printer << "buildPartialBlock(first: " << componentTypeString << ")";
break;
case ResultBuilderBuildFunction::BuildPartialBlockAccumulated:
printer << "buildPartialBlock(accumulated: " << componentTypeString
<< ", next: " << componentTypeString << ")";
break;
}
if (!printedResult)
printer << " -> " << componentTypeString;
if (stubIndent) {
printer << " {";
printer.printNewline();
printer << " <#code#>";
printer.printNewline();
printer << "}";
}
}
ResultBuilder::ResultBuilder(ConstraintSystem &CS, DeclContext *DC,
Type builderType)
: DC(DC), BuilderType(CS.simplifyType(builderType)) {
auto &ctx = DC->getASTContext();
// Use buildOptional(_:) if available, otherwise fall back to buildIf
// when available.
BuildOptionalId =
(supports(ctx.Id_buildOptional) || !supports(ctx.Id_buildIf))
? ctx.Id_buildOptional
: ctx.Id_buildIf;
BuilderSelf = new (ctx) VarDecl(
/*isStatic=*/false, VarDecl::Introducer::Let,
/*nameLoc=*/SourceLoc(), ctx.Id_builderSelf, DC);
BuilderSelf->setImplicit();
CS.setType(BuilderSelf, MetatypeType::get(BuilderType));
}
bool ResultBuilder::supportsBuildPartialBlock(bool checkAvailability) {
auto &ctx = DC->getASTContext();
return supports(ctx.Id_buildPartialBlock, {ctx.Id_first},
checkAvailability) &&
supports(ctx.Id_buildPartialBlock, {ctx.Id_accumulated, ctx.Id_next},
checkAvailability);
}
bool ResultBuilder::canUseBuildPartialBlock() {
// If buildPartialBlock doesn't exist at all, we can't use it.
if (!supportsBuildPartialBlock(/*checkAvailability*/ false))
return false;
// If buildPartialBlock exists and is available, use it.
if (supportsBuildPartialBlock(/*checkAvailability*/ true))
return true;
// We have buildPartialBlock, but it is unavailable. We can however still
// use it if buildBlock is also unavailable.
auto &ctx = DC->getASTContext();
return supports(ctx.Id_buildBlock) &&
!supports(ctx.Id_buildBlock, /*labels*/ {},
/*checkAvailability*/ true);
}
bool ResultBuilder::supports(Identifier fnBaseName,
ArrayRef<Identifier> argLabels,
bool checkAvailability) {
DeclName name(DC->getASTContext(), fnBaseName, argLabels);
auto known = SupportedOps.find(name);
if (known != SupportedOps.end())
return known->second.isSupported(checkAvailability);
auto support = TypeChecker::checkBuilderOpSupport(
BuilderType, DC, fnBaseName, argLabels, /*allResults*/ {});
SupportedOps.insert({name, support});
return support.isSupported(checkAvailability);
}
Expr *ResultBuilder::buildCall(SourceLoc loc, Identifier fnName,
ArrayRef<Expr *> argExprs,
ArrayRef<Identifier> argLabels) const {
assert(BuilderSelf);
auto &ctx = DC->getASTContext();
SmallVector<Argument, 4> args;
for (auto i : indices(argExprs)) {
auto *expr = argExprs[i];
auto label = argLabels.empty() ? Identifier() : argLabels[i];
auto labelLoc = argLabels.empty() ? SourceLoc() : expr->getStartLoc();
args.emplace_back(labelLoc, label, expr);
}
auto *baseExpr = new (ctx) DeclRefExpr({BuilderSelf}, DeclNameLoc(loc),
/*isImplicit=*/true);
auto memberRef = new (ctx)
UnresolvedDotExpr(baseExpr, loc, DeclNameRef(fnName), DeclNameLoc(loc),
/*implicit=*/true);
memberRef->setFunctionRefKind(FunctionRefKind::SingleApply);
auto openLoc = args.empty() ? loc : argExprs.front()->getStartLoc();
auto closeLoc = args.empty() ? loc : argExprs.back()->getEndLoc();
auto *argList = ArgumentList::createImplicit(ctx, openLoc, args, closeLoc);
return CallExpr::createImplicit(ctx, memberRef, argList);
}
VarDecl *ResultBuilder::buildVar(SourceLoc loc) {
auto &ctx = DC->getASTContext();
// Create the implicit variable.
Identifier name =
ctx.getIdentifier(("$__builder" + Twine(VarCounter++)).str());
auto var = new (ctx)
VarDecl(/*isStatic=*/false, VarDecl::Introducer::Var, loc, name, DC);
var->setImplicit();
return var;
}
DeclRefExpr *ResultBuilder::buildVarRef(VarDecl *var, SourceLoc loc) {
return new (DC->getASTContext())
DeclRefExpr(var, DeclNameLoc(loc), /*Implicit=*/true);
}
|