-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathBuilderTransform.cpp
1619 lines (1352 loc) · 57.3 KB
/
BuilderTransform.cpp
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
//===--- 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/Basic/Assertions.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()) {
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,
bool isolateBuildBlock = false) {
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=*/{});
if (isolateBuildBlock) {
auto *buildBlockVar = captureExpr(buildBlock, newBody);
return std::make_pair(
builder.buildVarRef(buildBlockVar, braceStmt->getStartLoc()),
std::nullopt);
}
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, /*isolateBuildBlock=*/true);
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, /*isolateBuildBlock=*/true);
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<CaseStmt *, 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();
NullablePtr<Expr> caseVarRef;
std::optional<UnsupportedElt> unsupported;
SmallVector<ASTNode, 4> newBody;
std::tie(caseVarRef, unsupported) =
transform(body, newBody, /*isolateBuildBlock=*/true);
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 startLoc = forEachStmt->getStartLoc();
SourceLoc endLoc = forEachStmt->getEndLoc();
// Build a variable that is going to hold array of results produced
// by each iteration of the loop. Note we need to give it the start loc of
// the for loop to ensure the implicit 'do' has a correct source range.
//
// Not that it's not going to be initialized here, that would happen
// only when a solution is found.
VarDecl *arrayVar = buildPlaceholderVar(
startLoc, doBody,
ArraySliceType::get(PlaceholderType::get(ctx, forEachVar.get())),
ArrayExpr::create(ctx, /*LBrace=*/startLoc, /*Elements=*/{},
/*Commas=*/{}, /*RBrace=*/startLoc));
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->setFunctionRefInfo(
FunctionRefInfo::singleBaseNameApply());
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->getUnsafeLoc(),
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) {
// First look for any return statements, and bail if we have any.
auto &ctx = func->getASTContext();
SmallVector<ReturnStmt *> returnStmts;
func->getExplicitReturnStmts(returnStmts);
if (!returnStmts.empty()) {
// One or more explicit 'return' statements were encountered, which
// disables the result builder transform. Warn when we do this.
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;
}
auto target = SyntacticElementTarget(func);
if (ConstraintSystem::preCheckTarget(target))
return nullptr;
ConstraintSystemOptions options = ConstraintSystemFlags::AllowFixes;
if (debugConstraintSolverForTarget(ctx, target))
options |= ConstraintSystemFlags::DebugConstraints;
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()->isOpaqueReturnTypeOf(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;
}