forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathBuilderTransform.cpp
1992 lines (1683 loc) · 69.6 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 - Function-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 function-builder
// transformation.
//
//===----------------------------------------------------------------------===//
#include "ConstraintSystem.h"
#include "MiscDiagnostics.h"
#include "SolutionResult.h"
#include "TypeChecker.h"
#include "TypeCheckAvailability.h"
#include "swift/Sema/IDETypeChecking.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 "llvm/ADT/DenseMap.h"
#include "llvm/ADT/SmallVector.h"
#include <iterator>
#include <map>
#include <memory>
#include <utility>
#include <tuple>
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:
continue;
case StmtConditionElement::CK_Availability:
return &cond;
break;
}
}
return nullptr;
}
/// Visitor to classify the contents of the given closure.
class BuilderClosureVisitor
: private StmtVisitor<BuilderClosureVisitor, VarDecl *> {
friend StmtVisitor<BuilderClosureVisitor, VarDecl *>;
ConstraintSystem *cs;
DeclContext *dc;
ASTContext &ctx;
Type builderType;
NominalTypeDecl *builder = nullptr;
Identifier buildOptionalId;
llvm::SmallDenseMap<Identifier, bool> supportedOps;
SkipUnhandledConstructInFunctionBuilder::UnhandledNode unhandledNode;
/// Whether an error occurred during application of the builder closure,
/// e.g., during constraint generation.
bool hadError = false;
/// Counter used to give unique names to the variables that are
/// created implicitly.
unsigned varCounter = 0;
/// The record of what happened when we applied the builder transform.
AppliedBuilderTransform applied;
/// Produce a builder call to the given named function with the given
/// arguments.
Expr *buildCallIfWanted(SourceLoc loc,
Identifier fnName, ArrayRef<Expr *> args,
ArrayRef<Identifier> argLabels) {
if (!cs)
return nullptr;
// FIXME: Setting a base on this expression is necessary in order
// to get diagnostics if something about this builder call fails,
// e.g. if there isn't a matching overload for `buildBlock`.
TypeExpr *typeExpr;
auto simplifiedTy = cs->simplifyType(builderType);
if (!simplifiedTy->hasTypeVariable()) {
typeExpr = TypeExpr::createImplicitHack(loc, simplifiedTy, ctx);
} else if (auto *decl = simplifiedTy->getAnyGeneric()) {
// HACK: If there's not enough information to completely resolve the
// builder type, but we have the base available to us, form an *explicit*
// TypeExpr pointing at it. We cannot form an implicit base without
// a fully-resolved concrete type. Really, whatever we put here has no
// bearing on the generated solution because we're going to use this node
// to stash the builder type and hand it back to the ambient
// constraint system.
typeExpr = TypeExpr::createForDecl(DeclNameLoc(loc), decl, dc);
} else {
// HACK: If there's not enough information in the constraint system,
// create a garbage base type to force it to diagnose
// this as an ambiguous expression.
// FIXME: We can also construct an UnresolvedMemberExpr here instead of
// an UnresolvedDotExpr and get a slightly better diagnostic.
typeExpr = TypeExpr::createImplicitHack(loc, ErrorType::get(ctx), ctx);
}
cs->setType(typeExpr, MetatypeType::get(builderType));
SmallVector<SourceLoc, 4> argLabelLocs;
for (auto i : indices(argLabels)) {
argLabelLocs.push_back(args[i]->getStartLoc());
}
auto memberRef = new (ctx) UnresolvedDotExpr(
typeExpr, loc, DeclNameRef(fnName), DeclNameLoc(loc),
/*implicit=*/true);
memberRef->setFunctionRefKind(FunctionRefKind::SingleApply);
SourceLoc openLoc = args.empty() ? loc : args.front()->getStartLoc();
SourceLoc closeLoc = args.empty() ? loc : args.back()->getEndLoc();
Expr *result = CallExpr::create(ctx, memberRef, openLoc, args,
argLabels, argLabelLocs, closeLoc,
/*trailing closures*/{},
/*implicit*/true);
return result;
}
/// Check whether the builder supports the given operation.
bool builderSupports(Identifier fnName,
ArrayRef<Identifier> argLabels = {}) {
auto known = supportedOps.find(fnName);
if (known != supportedOps.end()) {
return known->second;
}
return supportedOps[fnName] = TypeChecker::typeSupportsBuilderOp(
builderType, dc, fnName, argLabels);
}
/// Build an implicit variable in this context.
VarDecl *buildVar(SourceLoc loc) {
// Create the implicit variable.
Identifier name = ctx.getIdentifier(
("$__builder" + Twine(varCounter++)).str());
auto var = new (ctx) VarDecl(/*isStatic=*/false, VarDecl::Introducer::Var,
/*isCaptureList=*/false, loc, name, dc);
var->setImplicit();
return var;
}
/// Capture the given expression into an implicitly-generated variable.
VarDecl *captureExpr(Expr *expr, bool oneWay,
llvm::PointerUnion<Stmt *, Expr *> forEntity = nullptr) {
if (!cs)
return nullptr;
Expr *origExpr = expr;
if (oneWay) {
// Form a one-way constraint to prevent backward propagation.
expr = new (ctx) OneWayExpr(expr);
}
// Generate constraints for this expression.
expr = cs->generateConstraints(expr, dc);
if (!expr) {
hadError = true;
return nullptr;
}
// Create the implicit variable.
auto var = buildVar(expr->getStartLoc());
// Record the new variable and its corresponding expression & statement.
if (auto forStmt = forEntity.dyn_cast<Stmt *>()) {
applied.capturedStmts.insert({forStmt, { var, { expr } }});
} else {
if (auto forExpr = forEntity.dyn_cast<Expr *>())
origExpr = forExpr;
applied.capturedExprs.insert({origExpr, {var, expr}});
}
cs->setType(var, cs->getType(expr));
return var;
}
/// Build an implicit reference to the given variable.
DeclRefExpr *buildVarRef(VarDecl *var, SourceLoc loc) {
return new (ctx) DeclRefExpr(var, DeclNameLoc(loc), /*Implicit=*/true);
}
public:
BuilderClosureVisitor(ASTContext &ctx, ConstraintSystem *cs,
DeclContext *dc, Type builderType,
Type bodyResultType)
: cs(cs), dc(dc), ctx(ctx), builderType(builderType) {
builder = builderType->getAnyNominal();
applied.builderType = builderType;
applied.bodyResultType = bodyResultType;
// Use buildOptional(_:) if available, otherwise fall back to buildIf
// when available.
if (builderSupports(ctx.Id_buildOptional) ||
!builderSupports(ctx.Id_buildIf))
buildOptionalId = ctx.Id_buildOptional;
else
buildOptionalId = ctx.Id_buildIf;
}
/// Apply the builder transform to the given statement.
Optional<AppliedBuilderTransform> apply(Stmt *stmt) {
VarDecl *bodyVar = visit(stmt);
if (!bodyVar)
return None;
applied.returnExpr = buildVarRef(bodyVar, stmt->getEndLoc());
// If there is a buildFinalResult(_:), call it.
ASTContext &ctx = cs->getASTContext();
if (builderSupports(ctx.Id_buildFinalResult, { Identifier() })) {
applied.returnExpr = buildCallIfWanted(
applied.returnExpr->getLoc(), ctx.Id_buildFinalResult,
{ applied.returnExpr }, { Identifier() });
}
applied.returnExpr = cs->buildTypeErasedExpr(applied.returnExpr,
dc, applied.bodyResultType,
CTP_ReturnStmt);
applied.returnExpr = cs->generateConstraints(applied.returnExpr, dc);
if (!applied.returnExpr) {
hadError = true;
return None;
}
return std::move(applied);
}
/// Check whether the function builder can be applied to this statement.
/// \returns the node that cannot be handled by this builder on failure.
SkipUnhandledConstructInFunctionBuilder::UnhandledNode check(Stmt *stmt) {
(void)visit(stmt);
return unhandledNode;
}
protected:
#define CONTROL_FLOW_STMT(StmtClass) \
VarDecl *visit##StmtClass##Stmt(StmtClass##Stmt *stmt) { \
if (!unhandledNode) \
unhandledNode = stmt; \
\
return nullptr; \
}
void visitPatternBindingDecl(PatternBindingDecl *patternBinding) {
// If any of the entries lacks an initializer, don't handle this node.
if (!llvm::all_of(range(patternBinding->getNumPatternEntries()),
[&](unsigned index) {
return patternBinding->isExplicitlyInitialized(index);
})) {
if (!unhandledNode)
unhandledNode = patternBinding;
return;
}
// If there is a constraint system, generate constraints for the pattern
// binding.
if (cs) {
SolutionApplicationTarget target(patternBinding);
if (cs->generateConstraints(target, FreeTypeVariableBinding::Disallow))
hadError = true;
}
}
VarDecl *visitBraceStmt(BraceStmt *braceStmt) {
SmallVector<Expr *, 4> expressions;
auto addChild = [&](VarDecl *childVar) {
if (!childVar)
return;
expressions.push_back(buildVarRef(childVar, childVar->getLoc()));
};
for (auto node : braceStmt->getElements()) {
// Implicit returns in single-expression function bodies are treated
// as the expression.
if (auto returnStmt =
dyn_cast_or_null<ReturnStmt>(node.dyn_cast<Stmt *>())) {
assert(returnStmt->isImplicit());
node = returnStmt->getResult();
}
if (auto stmt = node.dyn_cast<Stmt *>()) {
addChild(visit(stmt));
continue;
}
if (auto decl = node.dyn_cast<Decl *>()) {
// Just ignore #if; the chosen children should appear in the
// surrounding context. This isn't good for source tools but it
// at least works.
if (isa<IfConfigDecl>(decl))
continue;
// Skip #warning/#error; we'll handle them when applying the builder.
if (isa<PoundDiagnosticDecl>(decl)) {
continue;
}
// Pattern bindings are okay so long as all of the entries are
// initialized.
if (auto patternBinding = dyn_cast<PatternBindingDecl>(decl)) {
visitPatternBindingDecl(patternBinding);
continue;
}
// Ignore variable declarations, because they're always handled within
// their enclosing pattern bindings.
if (isa<VarDecl>(decl))
continue;
if (!unhandledNode)
unhandledNode = decl;
continue;
}
auto expr = node.get<Expr *>();
if (cs && builderSupports(ctx.Id_buildExpression)) {
expr = buildCallIfWanted(expr->getLoc(), ctx.Id_buildExpression,
{ expr }, { Identifier() });
}
addChild(captureExpr(expr, /*oneWay=*/true, node.get<Expr *>()));
}
if (!cs || hadError)
return nullptr;
// Call Builder.buildBlock(... args ...)
auto call = buildCallIfWanted(braceStmt->getStartLoc(),
ctx.Id_buildBlock, expressions,
/*argLabels=*/{ });
if (!call)
return nullptr;
return captureExpr(call, /*oneWay=*/true, braceStmt);
}
VarDecl *visitReturnStmt(ReturnStmt *stmt) {
if (!unhandledNode)
unhandledNode = stmt;
return nullptr;
}
VarDecl *visitDoStmt(DoStmt *doStmt) {
auto childVar = visitBraceStmt(doStmt->getBody());
if (!childVar)
return nullptr;
auto childRef = buildVarRef(childVar, doStmt->getEndLoc());
return captureExpr(childRef, /*oneWay=*/true, doStmt);
}
CONTROL_FLOW_STMT(Yield)
CONTROL_FLOW_STMT(Defer)
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;
}
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 && !builderSupports(buildOptionalId))
return false;
// If there are multiple clauses, we need 'buildEither(first:)' and
// 'buildEither(second:)' to both exist.
if (numPayloads > 1) {
if (!builderSupports(ctx.Id_buildEither, {ctx.Id_first}) ||
!builderSupports(ctx.Id_buildEither, {ctx.Id_second}))
return false;
}
return true;
}
VarDecl *visitIfStmt(IfStmt *ifStmt) {
// Check whether the chain is buildable and whether it terminates
// without an `else`.
bool isOptional = false;
unsigned numPayloads = 0;
if (!isBuildableIfChain(ifStmt, numPayloads, isOptional)) {
if (!unhandledNode)
unhandledNode = ifStmt;
return nullptr;
}
// Attempt to build the chain, propagating short-circuits, which
// might arise either do to error or not wanting an expression.
return buildIfChainRecursive(ifStmt, 0, numPayloads, isOptional,
/*isTopLevel=*/true);
}
/// Recursively build an if-chain: build an expression which will have
/// a value of the chain result type before any call to `buildIf`.
/// The expression will perform any necessary calls to `buildEither`,
/// and the result will have optional type if `isOptional` is true.
VarDecl *buildIfChainRecursive(IfStmt *ifStmt, unsigned payloadIndex,
unsigned numPayloads, bool isOptional,
bool isTopLevel = false) {
assert(payloadIndex < numPayloads);
// First generate constraints for the conditions. This can introduce
// variable bindings that will be used within the "then" branch.
if (cs && cs->generateConstraints(ifStmt->getCond(), dc)) {
hadError = true;
return nullptr;
}
// Make sure we recursively visit both sides even if we're not
// building expressions.
// Build the then clause. This will have the corresponding payload
// type (i.e. not wrapped in any way).
VarDecl *thenVar = visit(ifStmt->getThenStmt());
// Build the else clause, if present. If this is from an else-if,
// this will be fully wrapped; otherwise it will have the corresponding
// payload type (at index `payloadIndex + 1`).
assert(ifStmt->getElseStmt() || isOptional);
bool isElseIf = false;
Optional<VarDecl *> elseChainVar;
if (auto elseStmt = ifStmt->getElseStmt()) {
if (auto elseIfStmt = dyn_cast<IfStmt>(elseStmt)) {
isElseIf = true;
elseChainVar = buildIfChainRecursive(elseIfStmt, payloadIndex + 1,
numPayloads, isOptional);
} else {
elseChainVar = visit(elseStmt);
}
}
// Short-circuit if appropriate.
if (!cs || !thenVar || (elseChainVar && !*elseChainVar))
return nullptr;
// If there is a #available in the condition, the 'then' will need to
// be wrapped in a call to buildLimitedAvailability(_:), if available.
Expr *thenVarRefExpr = buildVarRef(
thenVar, ifStmt->getThenStmt()->getEndLoc());
if (findAvailabilityCondition(ifStmt->getCond()) &&
builderSupports(ctx.Id_buildLimitedAvailability)) {
thenVarRefExpr = buildCallIfWanted(
ifStmt->getThenStmt()->getEndLoc(), ctx.Id_buildLimitedAvailability,
{ thenVarRefExpr }, { Identifier() });
}
// Prepare the `then` operand by wrapping it to produce a chain result.
Expr *thenExpr = buildWrappedChainPayload(
thenVarRefExpr, payloadIndex, numPayloads, isOptional);
// Prepare the `else operand:
Expr *elseExpr;
SourceLoc elseLoc;
// - If there's no `else` clause, use `Optional.none`.
if (!elseChainVar) {
assert(isOptional);
elseLoc = ifStmt->getEndLoc();
elseExpr = buildNoneExpr(elseLoc);
// - If there's an `else if`, the chain expression from that
// should already be producing a chain result.
} else if (isElseIf) {
elseExpr = buildVarRef(*elseChainVar, ifStmt->getEndLoc());
elseLoc = ifStmt->getElseLoc();
// - Otherwise, wrap it to produce a chain result.
} else {
elseLoc = ifStmt->getElseLoc();
elseExpr = buildWrappedChainPayload(
buildVarRef(*elseChainVar, ifStmt->getEndLoc()),
payloadIndex + 1, 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 && isTopLevel) {
thenExpr = buildCallIfWanted(ifStmt->getEndLoc(), buildOptionalId,
thenExpr, /*argLabels=*/{ });
elseExpr = buildCallIfWanted(ifStmt->getEndLoc(), buildOptionalId,
elseExpr, /*argLabels=*/{ });
}
thenExpr = cs->generateConstraints(thenExpr, dc);
if (!thenExpr) {
hadError = true;
return nullptr;
}
elseExpr = cs->generateConstraints(elseExpr, dc);
if (!elseExpr) {
hadError = true;
return nullptr;
}
Type resultType = cs->addJoinConstraint(cs->getConstraintLocator(ifStmt),
{
{ cs->getType(thenExpr), cs->getConstraintLocator(thenExpr) },
{ cs->getType(elseExpr), cs->getConstraintLocator(elseExpr) }
});
if (!resultType) {
hadError = true;
return nullptr;
}
// Create a variable to capture the result of this expression.
auto ifVar = buildVar(ifStmt->getStartLoc());
cs->setType(ifVar, resultType);
applied.capturedStmts.insert({ifStmt, { ifVar, { thenExpr, elseExpr }}});
return ifVar;
}
/// 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 = buildCallIfWanted(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);
return CallExpr::createImplicit(ctx, someRef, arg, { });
}
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);
}
VarDecl *visitSwitchStmt(SwitchStmt *switchStmt) {
// Generate constraints for the subject expression, and capture its
// type for use in matching the various patterns.
Expr *subjectExpr = switchStmt->getSubjectExpr();
if (cs) {
// Form a one-way constraint to prevent backward propagation.
subjectExpr = new (ctx) OneWayExpr(subjectExpr);
// FIXME: Add contextual type purpose for switch subjects?
SolutionApplicationTarget target(subjectExpr, dc, CTP_Unused, Type(),
/*isDiscarded=*/false);
if (cs->generateConstraints(target, FreeTypeVariableBinding::Disallow)) {
hadError = true;
return nullptr;
}
cs->setSolutionApplicationTarget(switchStmt, target);
subjectExpr = target.getAsExpr();
assert(subjectExpr && "Must have a subject expression here");
}
// Generate constraints and capture variables for all of the cases.
SmallVector<std::pair<CaseStmt *, VarDecl *>, 4> capturedCaseVars;
for (auto *caseStmt : switchStmt->getCases()) {
if (auto capturedCaseVar = visitCaseStmt(caseStmt, subjectExpr)) {
capturedCaseVars.push_back({caseStmt, capturedCaseVar});
}
}
if (!cs)
return nullptr;
// 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 (capturedCaseVars.empty()) {
TypeChecker::checkSwitchExhaustiveness(switchStmt, dc,
/*limitChecking=*/true);
hadError = true;
return nullptr;
}
// Form the expressions that inject the result of each case into the
// appropriate
llvm::TinyPtrVector<Expr *> injectedCaseExprs;
SmallVector<std::pair<Type, ConstraintLocator *>, 4> injectedCaseTerms;
for (unsigned idx : indices(capturedCaseVars)) {
auto caseStmt = capturedCaseVars[idx].first;
auto caseVar = capturedCaseVars[idx].second;
// Build the expression that injects the case variable into appropriate
// buildEither(first:)/buildEither(second:) chain.
Expr *caseVarRef = buildVarRef(caseVar, caseStmt->getEndLoc());
Expr *injectedCaseExpr = buildWrappedChainPayload(
caseVarRef, idx, capturedCaseVars.size(), /*isOptional=*/false);
// Generate constraints for this injected case result.
injectedCaseExpr = cs->generateConstraints(injectedCaseExpr, dc);
if (!injectedCaseExpr) {
hadError = true;
return nullptr;
}
// Record this injected case expression.
injectedCaseExprs.push_back(injectedCaseExpr);
// Record the type and locator for this injected case expression, to be
// used in the "join" constraint later.
injectedCaseTerms.push_back(
{ cs->getType(injectedCaseExpr)->getRValueType(),
cs->getConstraintLocator(injectedCaseExpr) });
}
// Form the type of the switch itself.
Type resultType = cs->addJoinConstraint(
cs->getConstraintLocator(switchStmt), injectedCaseTerms);
if (!resultType) {
hadError = true;
return nullptr;
}
// Create a variable to capture the result of evaluating the switch.
auto switchVar = buildVar(switchStmt->getStartLoc());
cs->setType(switchVar, resultType);
applied.capturedStmts.insert(
{switchStmt, { switchVar, std::move(injectedCaseExprs) } });
return switchVar;
}
VarDecl *visitCaseStmt(CaseStmt *caseStmt, Expr *subjectExpr) {
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) {
hadError = true;
return nullptr;
}
}
// If needed, generate constraints for everything in the case statement.
if (cs) {
auto locator = cs->getConstraintLocator(
subjectExpr, LocatorPathElt::ContextualType());
Type subjectType = cs->getType(subjectExpr);
if (cs->generateConstraints(caseStmt, dc, subjectType, locator)) {
hadError = true;
return nullptr;
}
}
// Translate the body.
return visit(caseStmt->getBody());
}
VarDecl *visitForEachStmt(ForEachStmt *forEachStmt) {
// for...in statements are handled via buildArray(_:); bail out if the
// builder does not support it.
if (!builderSupports(ctx.Id_buildArray)) {
if (!unhandledNode)
unhandledNode = forEachStmt;
return nullptr;
}
// 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 function-builder path entirely to let normal type checking
// take care of this.
auto sequenceProto = TypeChecker::getProtocol(
dc->getASTContext(), forEachStmt->getForLoc(),
KnownProtocolKind::Sequence);
if (!sequenceProto) {
if (!unhandledNode)
unhandledNode = forEachStmt;
return nullptr;
}
// Generate constraints for the loop header. This also wires up the
// types for the patterns.
auto target = SolutionApplicationTarget::forForEachStmt(
forEachStmt, sequenceProto, dc, /*bindPatternVarsOneWay=*/true);
if (cs) {
if (cs->generateConstraints(target, FreeTypeVariableBinding::Disallow)) {
hadError = true;
return nullptr;
}
cs->setSolutionApplicationTarget(forEachStmt, target);
}
// Visit the loop body itself.
VarDecl *bodyVar = visit(forEachStmt->getBody());
if (!bodyVar)
return nullptr;
// If there's no constraint system, there is nothing left to visit.
if (!cs)
return nullptr;
// Form a variable of array type that will capture the result of each
// iteration of the loop. We need a fresh type variable to remove the
// lvalue-ness of the array variable.
SourceLoc loc = forEachStmt->getForLoc();
VarDecl *arrayVar = buildVar(loc);
Type arrayElementType = cs->createTypeVariable(
cs->getConstraintLocator(forEachStmt), 0);
cs->addConstraint(
ConstraintKind::Equal, cs->getType(bodyVar), arrayElementType,
cs->getConstraintLocator(
forEachStmt, ConstraintLocator::RValueAdjustment));
Type arrayType = ArraySliceType::get(arrayElementType);
cs->setType(arrayVar, arrayType);
// Form an initialization of the array to an empty array literal.
Expr *arrayInitExpr = ArrayExpr::create(ctx, loc, { }, { }, loc);
cs->setContextualType(
arrayInitExpr, TypeLoc::withoutLoc(arrayType), CTP_CannotFail);
arrayInitExpr = cs->generateConstraints(arrayInitExpr, dc);
if (!arrayInitExpr) {
hadError = true;
return nullptr;
}
cs->addConstraint(
ConstraintKind::Equal, cs->getType(arrayInitExpr), arrayType,
cs->getConstraintLocator(
arrayInitExpr, LocatorPathElt::ContextualType()));
// Form a call to Array.append(_:) to add the result of executing each
// iteration of the loop body to the array formed above.
SourceLoc endLoc = forEachStmt->getEndLoc();
auto arrayVarRef = buildVarRef(arrayVar, endLoc);
auto arrayAppendRef = new (ctx) UnresolvedDotExpr(
arrayVarRef, endLoc, DeclNameRef(ctx.getIdentifier("append")),
DeclNameLoc(endLoc), /*implicit=*/true);
arrayAppendRef->setFunctionRefKind(FunctionRefKind::SingleApply);
auto bodyVarRef = buildVarRef(bodyVar, endLoc);
Expr *arrayAppendCall = CallExpr::create(
ctx, arrayAppendRef, endLoc, { bodyVarRef } , { Identifier() },
{ endLoc }, endLoc, /*trailingClosures=*/{}, /*implicit=*/true);
arrayAppendCall = cs->generateConstraints(arrayAppendCall, dc);
if (!arrayAppendCall) {
hadError = true;
return nullptr;
}
// Form the final call to buildArray(arrayVar) to allow the function
// builder to reshape the array into whatever it wants as the result of
// the for-each loop.
auto finalArrayVarRef = buildVarRef(arrayVar, endLoc);
auto buildArrayCall = buildCallIfWanted(
endLoc, ctx.Id_buildArray, { finalArrayVarRef }, { Identifier() });
assert(buildArrayCall);
buildArrayCall = cs->generateConstraints(buildArrayCall, dc);
if (!buildArrayCall) {
hadError = true;
return nullptr;
}
// Form a final variable for the for-each expression itself, which will
// be initialized with the call to the function builder's buildArray(_:).
auto finalForEachVar = buildVar(loc);
cs->setType(finalForEachVar, cs->getType(buildArrayCall));
applied.capturedStmts.insert(
{forEachStmt, {
finalForEachVar,
{ arrayVarRef, arrayInitExpr, arrayAppendCall, buildArrayCall }}});
return finalForEachVar;
}
/// Visit a throw statement, which never produces a result.
VarDecl *visitThrowStmt(ThrowStmt *throwStmt) {
Type exnType = ctx.getErrorDecl()->getDeclaredInterfaceType();
if (!exnType) {
hadError = true;
}
if (cs) {
SolutionApplicationTarget target(
throwStmt->getSubExpr(), dc, CTP_ThrowStmt, exnType,
/*isDiscarded=*/false);
if (cs->generateConstraints(target, FreeTypeVariableBinding::Disallow))
hadError = true;
cs->setSolutionApplicationTarget(throwStmt, target);
}
return nullptr;
}
CONTROL_FLOW_STMT(Guard)
CONTROL_FLOW_STMT(While)
CONTROL_FLOW_STMT(DoCatch)
CONTROL_FLOW_STMT(RepeatWhile)
CONTROL_FLOW_STMT(Case)
CONTROL_FLOW_STMT(Break)
CONTROL_FLOW_STMT(Continue)
CONTROL_FLOW_STMT(Fallthrough)
CONTROL_FLOW_STMT(Fail)
CONTROL_FLOW_STMT(PoundAssert)
#undef CONTROL_FLOW_STMT
};
/// Describes the target into which the result of a particular statement in
/// a closure involving a function builder should be written.
struct FunctionBuilderTarget {
enum Kind {
/// The resulting value is returned from the closure.
ReturnValue,
/// The temporary variable into which the result should be assigned.
TemporaryVar,
/// An expression to evaluate at the end of the block, allowing the update
/// of some state from an outer scope.
Expression,
} kind;
/// Captured variable information.
std::pair<VarDecl *, llvm::TinyPtrVector<Expr *>> captured;
static FunctionBuilderTarget forReturn(Expr *expr) {
return FunctionBuilderTarget{ReturnValue, {nullptr, {expr}}};
}
static FunctionBuilderTarget forAssign(VarDecl *temporaryVar,
llvm::TinyPtrVector<Expr *> exprs) {
return FunctionBuilderTarget{TemporaryVar, {temporaryVar, exprs}};
}
static FunctionBuilderTarget forExpression(Expr *expr) {
return FunctionBuilderTarget{Expression, { nullptr, { expr }}};
}
};
/// Handles the rewrite of the body of a closure to which a function builder
/// has been applied.
class BuilderClosureRewriter
: public StmtVisitor<BuilderClosureRewriter, Stmt *, FunctionBuilderTarget> {
ASTContext &ctx;
const Solution &solution;
DeclContext *dc;
AppliedBuilderTransform builderTransform;
std::function<
Optional<SolutionApplicationTarget> (SolutionApplicationTarget)>
rewriteTarget;
/// Retrieve the temporary variable that will be used to capture the
/// value of the given expression.
AppliedBuilderTransform::RecordedExpr takeCapturedExpr(Expr *expr) {
auto found = builderTransform.capturedExprs.find(expr);
assert(found != builderTransform.capturedExprs.end());
// Set the type of the temporary variable.
auto recorded = found->second;
if (auto temporaryVar = recorded.temporaryVar) {
Type type = solution.simplifyType(solution.getType(temporaryVar));
temporaryVar->setInterfaceType(type->mapTypeOutOfContext());
}
// Erase the captured expression, so we're sure we never do this twice.
builderTransform.capturedExprs.erase(found);
return recorded;
}
/// Rewrite an expression without any particularly special context.
Expr *rewriteExpr(Expr *expr) {
auto result = rewriteTarget(
SolutionApplicationTarget(expr, dc, CTP_Unused, Type(),
/*isDiscarded=*/false));
if (result)
return result->getAsExpr();
return nullptr;
}
public:
/// Retrieve information about a captured statement.
std::pair<VarDecl *, llvm::TinyPtrVector<Expr *>>
takeCapturedStmt(Stmt *stmt) {
auto found = builderTransform.capturedStmts.find(stmt);
assert(found != builderTransform.capturedStmts.end());
// Set the type of the temporary variable.
auto temporaryVar = found->second.first;
Type type = solution.simplifyType(solution.getType(temporaryVar));
temporaryVar->setInterfaceType(type->mapTypeOutOfContext());
// Take the expressions.
auto exprs = std::move(found->second.second);
// Erase the statement, so we're sure we never do this twice.
builderTransform.capturedStmts.erase(found);
return std::make_pair(temporaryVar, std::move(exprs));
}