-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathAsyncConverter.cpp
1886 lines (1685 loc) · 65.2 KB
/
AsyncConverter.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 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
//
//===----------------------------------------------------------------------===//
#include "AsyncRefactoring.h"
#include "Utils.h"
using namespace swift;
using namespace swift::refactoring::asyncrefactorings;
/// Base name of a decl if it has one, an empty \c DeclBaseName otherwise.
static DeclBaseName getDeclName(const Decl *D) {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
if (VD->hasName())
return VD->getBaseName();
}
return DeclBaseName();
}
bool AsyncConverter::convert() {
assert(Buffer.empty() && "AsyncConverter can only be used once");
if (auto *FD = dyn_cast_or_null<FuncDecl>(StartNode.dyn_cast<Decl *>())) {
addFuncDecl(FD);
if (FD->getBody()) {
convertNode(FD->getBody());
}
} else {
convertNode(StartNode, /*StartOverride=*/{}, /*ConvertCalls=*/true,
/*IncludeComments=*/false);
}
return !DiagEngine.hadAnyError();
}
bool AsyncConverter::createLegacyBody() {
assert(Buffer.empty() && "AsyncConverter can only be used once");
if (!canCreateLegacyBody())
return false;
FuncDecl *FD = cast<FuncDecl>(StartNode.get<Decl *>());
OS << tok::l_brace << "\n"; // start function body
OS << "Task " << tok::l_brace << "\n";
addHoistedNamedCallback(FD, TopHandler, TopHandler.getNameStr(), [&]() {
if (TopHandler.HasError) {
OS << tok::kw_try << " ";
}
OS << "await ";
// Since we're *creating* the async alternative here, there shouldn't
// already be one. Thus, just assume that the call to the alternative is
// the same as the call to the old completion handler function, minus the
// completion handler arg.
addForwardingCallTo(FD, /*HandlerReplacement=*/"");
});
OS << "\n";
OS << tok::r_brace << "\n"; // end 'Task'
OS << tok::r_brace << "\n"; // end function body
return true;
}
bool AsyncConverter::createAsyncWrapper() {
assert(Buffer.empty() && "AsyncConverter can only be used once");
auto *FD = cast<FuncDecl>(StartNode.get<Decl *>());
// First add the new async function declaration.
addFuncDecl(FD);
OS << tok::l_brace << "\n";
// Then add the body.
OS << tok::kw_return << " ";
if (TopHandler.HasError)
OS << tok::kw_try << " ";
OS << "await ";
// withChecked[Throwing]Continuation { continuation in
if (TopHandler.HasError) {
OS << "withCheckedThrowingContinuation";
} else {
OS << "withCheckedContinuation";
}
OS << " " << tok::l_brace << " continuation " << tok::kw_in << "\n";
// fnWithHandler(args...) { ... }
auto ClosureStr =
getAsyncWrapperCompletionClosure("continuation", TopHandler);
addForwardingCallTo(FD, /*HandlerReplacement=*/ClosureStr);
OS << "\n";
OS << tok::r_brace << "\n"; // end continuation closure
OS << tok::r_brace << "\n"; // end function body
return true;
}
void AsyncConverter::replace(ASTNode Node, SourceEditConsumer &EditConsumer,
SourceLoc StartOverride) {
SourceRange Range = Node.getSourceRange();
if (StartOverride.isValid()) {
Range = SourceRange(StartOverride, Range.End);
}
CharSourceRange CharRange =
Lexer::getCharSourceRangeFromSourceRange(SM, Range);
EditConsumer.accept(SM, CharRange, Buffer.str());
Buffer.clear();
}
void AsyncConverter::insertAfter(ASTNode Node,
SourceEditConsumer &EditConsumer) {
EditConsumer.insertAfter(SM, Node.getEndLoc(), "\n\n");
EditConsumer.insertAfter(SM, Node.getEndLoc(), Buffer.str());
Buffer.clear();
}
bool AsyncConverter::canCreateLegacyBody() {
FuncDecl *FD = dyn_cast<FuncDecl>(StartNode.dyn_cast<Decl *>());
if (!FD) {
return false;
}
if (FD == nullptr || FD->getBody() == nullptr) {
return false;
}
if (FD->hasThrows()) {
assert(!TopHandler.isValid() && "We shouldn't have found a handler desc "
"if the original function throws");
return false;
}
return TopHandler.isValid();
}
std::string AsyncConverter::getAsyncWrapperCompletionClosure(
StringRef ContName, const AsyncHandlerParamDesc &HandlerDesc) {
std::string OutputStr;
llvm::raw_string_ostream OS(OutputStr);
OS << tok::l_brace; // start closure
// Prepare parameter names for the closure.
auto SuccessParams = HandlerDesc.getSuccessParams();
SmallVector<SmallString<4>, 2> SuccessParamNames;
for (auto idx : indices(SuccessParams)) {
SuccessParamNames.emplace_back("result");
// If we have multiple success params, number them e.g res1, res2...
if (SuccessParams.size() > 1)
SuccessParamNames.back().append(std::to_string(idx + 1));
}
llvm::Optional<SmallString<4>> ErrName;
if (HandlerDesc.getErrorParam())
ErrName.emplace("error");
auto HasAnyParams = !SuccessParamNames.empty() || ErrName;
if (HasAnyParams)
OS << " ";
// res1, res2
llvm::interleave(
SuccessParamNames, [&](auto Name) { OS << Name; },
[&]() { OS << tok::comma << " "; });
// , err
if (ErrName) {
if (!SuccessParamNames.empty())
OS << tok::comma << " ";
OS << *ErrName;
}
if (HasAnyParams)
OS << " " << tok::kw_in;
OS << "\n";
// The closure body.
switch (HandlerDesc.Type) {
case HandlerType::PARAMS: {
// For a (Success?, Error?) -> Void handler, we do an if let on the error.
if (ErrName) {
// if let err = err {
OS << tok::kw_if << " " << tok::kw_let << " ";
OS << *ErrName << " " << tok::equal << " " << *ErrName << " ";
OS << tok::l_brace << "\n";
for (auto Idx : indices(SuccessParamNames)) {
auto ParamTy = SuccessParams[Idx].getParameterType();
if (!HandlerDesc.shouldUnwrap(ParamTy))
continue;
}
// continuation.resume(throwing: err)
OS << ContName << tok::period << "resume" << tok::l_paren;
OS << "throwing" << tok::colon << " " << *ErrName;
OS << tok::r_paren << "\n";
// return }
OS << tok::kw_return << "\n";
OS << tok::r_brace << "\n";
}
// If we have any success params that we need to unwrap, insert a guard.
for (auto Idx : indices(SuccessParamNames)) {
auto &Name = SuccessParamNames[Idx];
auto ParamTy = SuccessParams[Idx].getParameterType();
if (!HandlerDesc.shouldUnwrap(ParamTy))
continue;
// guard let res = res else {
OS << tok::kw_guard << " " << tok::kw_let << " ";
OS << Name << " " << tok::equal << " " << Name << " " << tok::kw_else;
OS << " " << tok::l_brace << "\n";
// fatalError(...)
OS << "fatalError" << tok::l_paren;
OS << "\"Expected non-nil result '" << Name << "' for nil error\"";
OS << tok::r_paren << "\n";
// End guard.
OS << tok::r_brace << "\n";
}
// continuation.resume(returning: (res1, res2, ...))
OS << ContName << tok::period << "resume" << tok::l_paren;
OS << "returning" << tok::colon << " ";
addTupleOf(SuccessParamNames, OS, [&](auto Ref) { OS << Ref; });
OS << tok::r_paren << "\n";
break;
}
case HandlerType::RESULT: {
// continuation.resume(with: res)
assert(SuccessParamNames.size() == 1);
OS << ContName << tok::period << "resume" << tok::l_paren;
OS << "with" << tok::colon << " " << SuccessParamNames[0];
OS << tok::r_paren << "\n";
break;
}
case HandlerType::INVALID:
llvm_unreachable("Should not have an invalid handler here");
}
OS << tok::r_brace; // end closure
return OutputStr;
}
CharSourceRange AsyncConverter::getPrecedingCommentRange(SourceLoc Loc) {
auto Tokens = SF->getAllTokens();
auto TokenIter = token_lower_bound(Tokens, Loc);
if (TokenIter == Tokens.end() || !TokenIter->hasComment())
return CharSourceRange();
return TokenIter->getCommentRange();
}
SourceLoc AsyncConverter::getLocIncludingPrecedingComment(SourceLoc Loc) {
auto CommentRange = getPrecedingCommentRange(Loc);
if (CommentRange.isInvalid())
return Loc;
return CommentRange.getStart();
}
void AsyncConverter::printCommentIfNeeded(SourceLoc Loc) {
auto CommentRange = getPrecedingCommentRange(Loc);
if (CommentRange.isValid())
OS << "\n" << CommentRange.str();
}
void AsyncConverter::convertNodes(const NodesToPrint &ToPrint) {
// Sort the possible comment locs in reverse order so we can pop them as we
// go.
SmallVector<SourceLoc, 2> CommentLocs;
CommentLocs.append(ToPrint.getPossibleCommentLocs().begin(),
ToPrint.getPossibleCommentLocs().end());
llvm::sort(CommentLocs.begin(), CommentLocs.end(), [](auto lhs, auto rhs) {
return lhs.getOpaquePointerValue() > rhs.getOpaquePointerValue();
});
// First print the nodes we've been asked to print.
for (auto Node : ToPrint.getNodes()) {
// If we need to print comments, do so now.
while (!CommentLocs.empty()) {
auto CommentLoc = CommentLocs.back().getOpaquePointerValue();
auto NodeLoc = Node.getStartLoc().getOpaquePointerValue();
assert(CommentLoc != NodeLoc &&
"Added node to both comment locs and nodes to print?");
// If the comment occurs after the node, don't print now. Wait until
// the right node comes along.
if (CommentLoc > NodeLoc)
break;
printCommentIfNeeded(CommentLocs.pop_back_val());
}
OS << "\n";
convertNode(Node);
}
// We're done printing nodes. Make sure to output the remaining comments.
while (!CommentLocs.empty())
printCommentIfNeeded(CommentLocs.pop_back_val());
}
void AsyncConverter::convertNode(ASTNode Node, SourceLoc StartOverride,
bool ConvertCalls,
bool IncludePrecedingComment) {
if (!StartOverride.isValid())
StartOverride = Node.getStartLoc();
// Make sure to include any preceding comments attached to the loc
if (IncludePrecedingComment)
StartOverride = getLocIncludingPrecedingComment(StartOverride);
llvm::SaveAndRestore<SourceLoc> RestoreLoc(LastAddedLoc, StartOverride);
llvm::SaveAndRestore<int> RestoreCount(NestedExprCount, ConvertCalls ? 0 : 1);
walk(Node);
addRange(LastAddedLoc, Node.getEndLoc(), /*ToEndOfToken=*/true);
}
void AsyncConverter::convertPattern(const Pattern *P) {
// Only print semantic patterns. This cleans up the output of the transform
// and works around some bogus source locs that can appear with typed
// patterns in if let statements.
P = P->getSemanticsProvidingPattern();
// Set up the start of the pattern as the last loc printed to make sure we
// accurately fill in the gaps as we customize the printing of sub-patterns.
llvm::SaveAndRestore<SourceLoc> RestoreLoc(LastAddedLoc, P->getStartLoc());
llvm::SaveAndRestore<bool> RestoreFlag(ConvertingPattern, true);
walk(const_cast<Pattern *>(P));
addRange(LastAddedLoc, P->getEndLoc(), /*ToEndOfToken*/ true);
}
void AsyncConverter::wrapScopeInContinationIfNecessary(ASTNode Node) {
if (NestedExprCount != 0) {
// We can't start a continuation in the middle of an expression
return;
}
if (Scopes.back().isWrappedInContination()) {
// We are already in a continuation. No need to add another one.
return;
}
if (!DeclReferenceFinder::containsReference(Node, TopHandler.getHandler())) {
// The node doesn't have a reference to the function's completion handler.
// It can stay a call with a completion handler, because we don't need to
// promote a completion handler call to a 'return'.
return;
}
// Wrap the current call in a continuation
Identifier contName = createUniqueName("continuation");
Scopes.back().Names.insert(contName);
Scopes.back().ContinuationName = contName;
insertCustom(Node.getStartLoc(), [&]() {
OS << tok::kw_return << ' ';
if (TopHandler.HasError) {
OS << tok::kw_try << ' ';
}
OS << "await ";
if (TopHandler.HasError) {
OS << "withCheckedThrowingContinuation ";
} else {
OS << "withCheckedContinuation ";
}
OS << tok::l_brace << ' ' << contName << ' ' << tok::kw_in << '\n';
});
}
bool AsyncConverter::walkToPatternPre(Pattern *P) {
// If we're not converting a pattern, there's nothing extra to do.
if (!ConvertingPattern)
return true;
// When converting a pattern, don't print the 'let' or 'var' of binding
// subpatterns, as they're illegal when nested in PBDs, and we print a
// top-level one.
if (auto *BP = dyn_cast<BindingPattern>(P)) {
return addCustom(BP->getSourceRange(),
[&]() { convertPattern(BP->getSubPattern()); });
}
return true;
}
bool AsyncConverter::walkToDeclPre(Decl *D, CharSourceRange Range) {
if (isa<PatternBindingDecl>(D)) {
// We can't hoist a closure inside a PatternBindingDecl. If it contains
// a call to the completion handler, wrap it in a continuation.
wrapScopeInContinationIfNecessary(D);
NestedExprCount++;
return true;
}
// Functions and types already have their names in \c Scopes.Names, only
// variables should need to be renamed.
if (isa<VarDecl>(D)) {
// If we don't already have a name for the var, assign it one. Note that
// vars in binding patterns may already have assigned names here.
if (Names.find(D) == Names.end()) {
auto Ident = assignUniqueName(D, StringRef());
Scopes.back().Names.insert(Ident);
}
addCustom(D->getSourceRange(), [&]() { OS << newNameFor(D); });
}
// Note we don't walk into any nested local function decls. If we start
// doing so in the future, be sure to update the logic that deals with
// converting unhandled returns into placeholders in walkToStmtPre.
return false;
}
bool AsyncConverter::walkToDeclPost(Decl *D) {
NestedExprCount--;
return true;
}
#define PLACEHOLDER_START "<#"
#define PLACEHOLDER_END "#>"
bool AsyncConverter::walkToExprPre(Expr *E) {
// TODO: Handle Result.get as well
if (auto *DRE = dyn_cast<DeclRefExpr>(E)) {
if (auto *D = DRE->getDecl()) {
// Look through to the parent var decl if we have one. This ensures we
// look at the var in a case stmt's pattern rather than the var that's
// implicitly declared in the body.
if (auto *VD = dyn_cast<VarDecl>(D)) {
if (auto *Parent = VD->getParentVarDecl())
D = Parent;
}
bool AddPlaceholder = Placeholders.count(D);
StringRef Name = newNameFor(D, false);
if (AddPlaceholder || !Name.empty())
return addCustom(DRE->getSourceRange(), [&]() {
if (AddPlaceholder)
OS << PLACEHOLDER_START;
if (!Name.empty())
OS << Name;
else
D->getName().print(OS);
if (AddPlaceholder)
OS << PLACEHOLDER_END;
});
}
} else if (isa<ForceValueExpr>(E) || isa<BindOptionalExpr>(E)) {
// Remove a force unwrap or optional chain of a returned success value,
// as it will no longer be optional. For force unwraps, this is always a
// valid transform. For optional chains, it is a locally valid transform
// within the optional chain e.g foo?.x -> foo.x, but may change the type
// of the overall chain, which could cause errors elsewhere in the code.
// However this is generally more useful to the user than just leaving
// 'foo' as a placeholder. Note this is only the case when no other
// optionals are involved in the chain, e.g foo?.x?.y -> foo.x?.y is
// completely valid.
if (auto *D = E->getReferencedDecl().getDecl()) {
if (Unwraps.count(D))
return addCustom(E->getSourceRange(),
[&]() { OS << newNameFor(D, true); });
}
} else if (CallExpr *CE = TopHandler.getAsHandlerCall(E)) {
if (Scopes.back().isWrappedInContination()) {
return addCustom(E->getSourceRange(),
[&]() { convertHandlerToContinuationResume(CE); });
} else if (NestedExprCount == 0) {
return addCustom(E->getSourceRange(),
[&]() { convertHandlerToReturnOrThrows(CE); });
}
} else if (auto *CE = dyn_cast<CallExpr>(E)) {
// Try and hoist a call's completion handler. Don't do so if
// - the current expression is nested (we can't start hoisting in the
// middle of an expression)
// - the current scope is wrapped in a continuation (we can't have await
// calls in the continuation block)
if (NestedExprCount == 0 && !Scopes.back().isWrappedInContination()) {
// If the refactoring is on the call itself, do not require the callee
// to have the @available attribute or a completion-like name.
auto HandlerDesc = AsyncHandlerParamDesc::find(
getUnderlyingFunc(CE->getFn()),
/*RequireAttributeOrName=*/StartNode.dyn_cast<Expr *>() != CE);
if (HandlerDesc.isValid()) {
return addCustom(CE->getSourceRange(),
[&]() { addHoistedCallback(CE, HandlerDesc); });
}
}
}
// A void SingleValueStmtExpr is semantically more like a statement than
// an expression, so recurse without bumping the expr depth or wrapping in
// continuation.
if (auto *SVE = dyn_cast<SingleValueStmtExpr>(E)) {
auto ty = SVE->getType();
if (!ty || ty->isVoid())
return true;
}
// We didn't do any special conversion for this expression. If needed, wrap
// it in a continuation.
wrapScopeInContinationIfNecessary(E);
NestedExprCount++;
return true;
}
bool AsyncConverter::replaceRangeWithPlaceholder(SourceRange range) {
return addCustom(range, [&]() {
OS << PLACEHOLDER_START;
addRange(range, /*toEndOfToken*/ true);
OS << PLACEHOLDER_END;
});
}
bool AsyncConverter::walkToExprPost(Expr *E) {
if (auto *SVE = dyn_cast<SingleValueStmtExpr>(E)) {
auto ty = SVE->getType();
if (!ty || ty->isVoid())
return true;
}
NestedExprCount--;
return true;
}
#undef PLACEHOLDER_START
#undef PLACEHOLDER_END
bool AsyncConverter::walkToStmtPre(Stmt *S) {
// CaseStmt has an implicit BraceStmt inside it, which *should* start a new
// scope, so don't check isImplicit here.
if (startsNewScope(S)) {
// Add all names of decls referenced within this statement that aren't
// also declared first, plus any contexts. Note that \c getReferencedDecl
// will only return a value for a \c BraceStmt. This means that \c IfStmt
// (and other statements with conditions) will have their own empty scope,
// which is fine for our purposes - their existing names are always valid.
// The body of those statements will include the decls if they've been
// referenced, so shadowing is still avoided there.
if (auto *ReferencedDecls = ScopedDecls.getReferencedDecls(S)) {
llvm::DenseSet<const Decl *> Decls;
for (auto DeclAndNumRefs : *ReferencedDecls)
Decls.insert(DeclAndNumRefs.first);
addNewScope(Decls);
} else {
addNewScope({});
}
} else if (Hoisting && !S->isImplicit()) {
// Some break and return statements need to be turned into placeholders,
// as they may no longer perform the control flow that the user is
// expecting.
if (auto *BS = dyn_cast<BreakStmt>(S)) {
// For a break, if it's jumping out of a switch statement that we've
// re-written as a part of the transform, turn it into a placeholder, as
// it would have been lifted out of the switch statement.
if (auto *SS = dyn_cast<SwitchStmt>(BS->getTarget())) {
if (HandledSwitches.contains(SS))
return replaceRangeWithPlaceholder(S->getSourceRange());
}
} else if (isa<ReturnStmt>(S) && NestedExprCount == 0) {
// For a return, if it's not nested inside another closure or function,
// turn it into a placeholder, as it will be lifted out of the callback.
// Note that we only turn the 'return' token into a placeholder as we
// still want to be able to apply transforms to the argument.
replaceRangeWithPlaceholder(S->getStartLoc());
}
}
return true;
}
bool AsyncConverter::walkToStmtPost(Stmt *S) {
if (startsNewScope(S)) {
bool ClosedScopeWasWrappedInContinuation =
Scopes.back().isWrappedInContination();
Scopes.pop_back();
if (ClosedScopeWasWrappedInContinuation &&
!Scopes.back().isWrappedInContination()) {
// The nested scope was wrapped in a continuation but the current one
// isn't anymore. Add the '}' that corresponds to the the call to
// withChecked(Throwing)Continuation.
insertCustom(S->getEndLoc(), [&]() { OS << tok::r_brace << '\n'; });
}
}
return true;
}
bool AsyncConverter::addCustom(SourceRange Range,
llvm::function_ref<void()> Custom) {
addRange(LastAddedLoc, Range.Start);
Custom();
LastAddedLoc = Lexer::getLocForEndOfToken(SM, Range.End);
return false;
}
bool AsyncConverter::insertCustom(SourceLoc Loc,
llvm::function_ref<void()> Custom) {
addRange(LastAddedLoc, Loc);
Custom();
LastAddedLoc = Loc;
return false;
}
void AsyncConverter::addRange(SourceLoc Start, SourceLoc End,
bool ToEndOfToken) {
if (ToEndOfToken) {
OS << Lexer::getCharSourceRangeFromSourceRange(SM, SourceRange(Start, End))
.str();
} else {
OS << CharSourceRange(SM, Start, End).str();
}
}
void AsyncConverter::addRange(SourceRange Range, bool ToEndOfToken) {
addRange(Range.Start, Range.End, ToEndOfToken);
}
void AsyncConverter::addFuncDecl(const FuncDecl *FD) {
auto *Params = FD->getParameters();
auto *HandlerParam = TopHandler.getHandlerParam();
auto ParamPos = TopHandler.handlerParamPosition();
// If the completion handler parameter has a default argument, the async
// version is effectively @discardableResult, as not all the callers care
// about receiving the completion call.
if (HandlerParam && HandlerParam->isDefaultArgument())
OS << tok::at_sign << "discardableResult"
<< "\n";
// First chunk: start -> the parameter to remove (if any)
SourceLoc LeftEndLoc;
switch (ParamPos) {
case AsyncHandlerParamDesc::Position::None:
case AsyncHandlerParamDesc::Position::Only:
case AsyncHandlerParamDesc::Position::First:
// Handler is the first param (or there is none), so only include the (
LeftEndLoc = Params->getLParenLoc().getAdvancedLoc(1);
break;
case AsyncHandlerParamDesc::Position::Middle:
// Handler is somewhere in the middle of the params, so we need to
// include any comments and comma up until the handler
LeftEndLoc = Params->get(TopHandler.Index)->getStartLoc();
LeftEndLoc = getLocIncludingPrecedingComment(LeftEndLoc);
break;
case AsyncHandlerParamDesc::Position::Last:
// Handler is the last param, which means we don't want the comma. This
// is a little annoying since we *do* want the comments past for the
// last parameter
LeftEndLoc = Lexer::getLocForEndOfToken(
SM, Params->get(TopHandler.Index - 1)->getEndLoc());
// Skip to the end of any comments
Token Next =
Lexer::getTokenAtLocation(SM, LeftEndLoc, CommentRetentionMode::None);
if (Next.getKind() != tok::NUM_TOKENS)
LeftEndLoc = Next.getLoc();
break;
}
addRange(FD->getSourceRangeIncludingAttrs().Start, LeftEndLoc);
// Second chunk: end of the parameter to remove -> right parenthesis
SourceLoc MidStartLoc;
SourceLoc MidEndLoc = Params->getRParenLoc().getAdvancedLoc(1);
switch (ParamPos) {
case AsyncHandlerParamDesc::Position::None:
// No handler param, so make sure to include them all
MidStartLoc = LeftEndLoc;
break;
case AsyncHandlerParamDesc::Position::First:
case AsyncHandlerParamDesc::Position::Middle:
// Handler param is either the first or one of the middle params. Skip
// past it but make sure to include comments preceding the param after
// the handler
MidStartLoc = Params->get(TopHandler.Index + 1)->getStartLoc();
MidStartLoc = getLocIncludingPrecedingComment(MidStartLoc);
break;
case AsyncHandlerParamDesc::Position::Only:
case AsyncHandlerParamDesc::Position::Last:
// Handler param is last, this is easy since there's no other params
// to copy over
MidStartLoc = Params->getRParenLoc();
break;
}
addRange(MidStartLoc, MidEndLoc);
// Third chunk: add in async and throws if necessary
if (!FD->hasAsync())
OS << " async";
if (FD->hasThrows() || TopHandler.HasError)
// TODO: Add throws if converting a function and it has a converted call
// without a do/catch
OS << " " << tok::kw_throws;
// Fourth chunk: if no parent handler (ie. not adding an async
// alternative), the rest of the decl. Otherwise, add in the new return
// type
if (!TopHandler.isValid()) {
SourceLoc RightStartLoc = MidEndLoc;
if (FD->hasThrows()) {
RightStartLoc = Lexer::getLocForEndOfToken(SM, FD->getThrowsLoc());
}
SourceLoc RightEndLoc =
FD->getBody() ? FD->getBody()->getLBraceLoc() : RightStartLoc;
addRange(RightStartLoc, RightEndLoc);
return;
}
SmallVector<LabeledReturnType, 2> Scratch;
auto ReturnTypes = TopHandler.getAsyncReturnTypes(Scratch);
if (ReturnTypes.empty()) {
OS << " ";
return;
}
// Print the function result type, making sure to omit a '-> Void' return.
if (!TopHandler.willAsyncReturnVoid()) {
OS << " -> ";
addAsyncFuncReturnType(TopHandler);
}
if (FD->hasBody())
OS << " ";
// TODO: Should remove the generic param and where clause for the error
// param if it exists (and no other parameter uses that type)
TrailingWhereClause *TWC = FD->getTrailingWhereClause();
if (TWC && TWC->getWhereLoc().isValid()) {
auto Range = TWC->getSourceRange();
OS << Lexer::getCharSourceRangeFromSourceRange(SM, Range).str();
if (FD->hasBody())
OS << " ";
}
}
void AsyncConverter::addFallbackVars(ArrayRef<const ParamDecl *> FallbackParams,
const ClosureCallbackParams &AllParams) {
for (auto *Param : FallbackParams) {
auto Ty = Param->getTypeInContext();
auto ParamName = newNameFor(Param);
// If this is the known bool success param, we can use 'let' and type it
// as non-optional, as it gets bound in both blocks.
if (AllParams.isKnownBoolFlagParam(Param)) {
OS << tok::kw_let << " " << ParamName << ": ";
Ty->print(OS);
OS << "\n";
continue;
}
OS << tok::kw_var << " " << ParamName << ": ";
Ty->print(OS);
if (!Ty->getOptionalObjectType())
OS << "?";
OS << " = " << tok::kw_nil << "\n";
}
}
void AsyncConverter::addDo() {
OS << tok::kw_do << " " << tok::l_brace << "\n";
}
bool AsyncConverter::isErrorAlreadyHandled(HandlerResult Result) {
assert(Result.isError());
assert(Result.args().size() == 1 &&
"There should only be one error parameter");
// We assume that the error has already been handled if its variable
// declaration doesn't exist anymore, which is the case if it's in
// Placeholders but not in Unwraps (if it's in Placeholders and Unwraps
// an optional Error has simply been promoted to a non-optional Error).
if (auto *DRE = dyn_cast<DeclRefExpr>(Result.args().back().getExpr())) {
if (Placeholders.count(DRE->getDecl()) && !Unwraps.count(DRE->getDecl())) {
return true;
}
}
return false;
}
bool AsyncConverter::isExpressionOptional(Expr *E) {
if (isa<InjectIntoOptionalExpr>(E)) {
// E is downgrading a non-Optional result to an Optional. Its source
// representation isn't Optional.
return false;
}
if (auto DRE = dyn_cast<DeclRefExpr>(E)) {
if (Unwraps.count(DRE->getDecl())) {
// E has been promoted to a non-Optional value. It can't be used as an
// Optional anymore.
return false;
}
}
if (!E->getType().isNull() && E->getType()->isOptional()) {
return true;
}
// We couldn't determine the type. Assume non-Optional.
return false;
}
void AsyncConverter::convertHandlerCall(
const CallExpr *CE,
llvm::function_ref<void(HandlerResult)> AddConvertedHandlerCall,
llvm::function_ref<void(StringRef)> AddConvertedErrorCall) {
auto Result =
TopHandler.extractResultArgs(CE, /*ReturnErrorArgsIfAmbiguous=*/true);
if (!TopHandler.isAmbiguousCallToParamHandler(CE)) {
if (Result.isError()) {
if (!isErrorAlreadyHandled(Result)) {
// If the error has already been handled, we don't need to add another
// throwing call.
AddConvertedHandlerCall(Result);
}
} else {
AddConvertedHandlerCall(Result);
}
} else {
assert(Result.isError() && "If the call was ambiguous, we should have "
"retrieved its error representation");
assert(Result.args().size() == 1 &&
"There should only be one error parameter");
Expr *ErrorExpr = Result.args().back().getExpr();
if (isErrorAlreadyHandled(Result)) {
// The error has already been handled, interpret the call as a success
// call.
auto SuccessExprs = TopHandler.extractResultArgs(
CE, /*ReturnErrorArgsIfAmbiguous=*/false);
AddConvertedHandlerCall(SuccessExprs);
} else if (!isExpressionOptional(ErrorExpr)) {
// The error is never nil. No matter what the success param is, we
// interpret it as an error call.
AddConvertedHandlerCall(Result);
} else {
// The call was truly ambiguous. Add an
// if let error = <convert error arg> {
// throw error // or equivalent
// } else {
// <interpret call as success call>
// }
auto SuccessExprs = TopHandler.extractResultArgs(
CE, /*ReturnErrorArgsIfAmbiguous=*/false);
// The variable 'error' is only available in the 'if let' scope, so we
// don't need to create a new unique one.
StringRef ErrorName = "error";
OS << tok::kw_if << ' ' << tok::kw_let << ' ' << ErrorName << ' '
<< tok::equal << ' ';
convertNode(ErrorExpr, /*StartOverride=*/{}, /*ConvertCalls=*/false);
OS << ' ' << tok::l_brace << '\n';
AddConvertedErrorCall(ErrorName);
OS << tok::r_brace << ' ' << tok::kw_else << ' ' << tok::l_brace << '\n';
AddConvertedHandlerCall(SuccessExprs);
OS << '\n' << tok::r_brace;
}
}
}
void AsyncConverter::convertHandlerToReturnOrThrows(const CallExpr *CE) {
return convertHandlerCall(
CE,
[&](HandlerResult Exprs) {
convertHandlerToReturnOrThrowsImpl(CE, Exprs);
},
[&](StringRef ErrorName) {
OS << tok::kw_throw << ' ' << ErrorName << '\n';
});
}
void AsyncConverter::convertHandlerToReturnOrThrowsImpl(const CallExpr *CE,
HandlerResult Result) {
bool AddedReturnOrThrow = true;
if (!Result.isError()) {
// It's possible the user has already written an explicit return statement
// for the completion handler call, e.g 'return completion(args...)'. In
// that case, be sure not to add another return.
auto *parent = getWalker().Parent.getAsStmt();
if (isa_and_nonnull<ReturnStmt>(parent) &&
!cast<ReturnStmt>(parent)->isImplicit()) {
// The statement already has a return keyword. Don't add another one.
AddedReturnOrThrow = false;
} else {
OS << tok::kw_return;
}
} else {
OS << tok::kw_throw;
}
auto Args = Result.args();
if (!Args.empty()) {
if (AddedReturnOrThrow)
OS << ' ';
addTupleOf(Args, OS, [&](Argument Arg) {
// Special case: If the completion handler is a params handler that
// takes an error, we could pass arguments to it without unwrapping
// them. E.g.
// simpleWithError { (res: String?, error: Error?) in
// completion(res, nil)
// }
// But after refactoring `simpleWithError` to an async function we have
// let res: String = await simple()
// and `res` is no longer an `Optional`. Thus it's in `Placeholders` and
// `Unwraps` and any reference to it will be replaced by a placeholder
// unless it is wrapped in an unwrapping expression. This would cause us
// to create `return <#res# >`.
// Under our assumption that either the error or the result parameter
// are non-nil, the above call to the completion handler is equivalent
// to
// completion(res!, nil)
// which correctly yields
// return res
// Synthesize the force unwrap so that we get the expected results.
auto *E = Arg.getExpr();
if (TopHandler.getHandlerType() == HandlerType::PARAMS &&
TopHandler.HasError) {
if (auto DRE = dyn_cast<DeclRefExpr>(E->getSemanticsProvidingExpr())) {
auto D = DRE->getDecl();
if (Unwraps.count(D)) {
E = new (getASTContext()) ForceValueExpr(E, SourceLoc());
}
}
}
// Can't just add the range as we need to perform replacements
convertNode(E, /*StartOverride=*/Arg.getLabelLoc(),
/*ConvertCalls=*/false);
});
}
}
void AsyncConverter::convertHandlerToContinuationResume(const CallExpr *CE) {
return convertHandlerCall(
CE,
[&](HandlerResult Exprs) {
convertHandlerToContinuationResumeImpl(CE, Exprs);
},
[&](StringRef ErrorName) {
Identifier ContinuationName = Scopes.back().ContinuationName;
OS << ContinuationName << tok::period << "resume" << tok::l_paren
<< "throwing" << tok::colon << ' ' << ErrorName;
OS << tok::r_paren << '\n';
});
}
void AsyncConverter::convertHandlerToContinuationResumeImpl(
const CallExpr *CE, HandlerResult Result) {
assert(Scopes.back().isWrappedInContination());
std::vector<Argument> Args;
StringRef ResumeArgumentLabel;
switch (TopHandler.getHandlerType()) {
case HandlerType::PARAMS: {
Args = Result.args();
if (!Result.isError()) {
ResumeArgumentLabel = "returning";
} else {
ResumeArgumentLabel = "throwing";
}
break;
}
case HandlerType::RESULT: {
Args = {CE->getArgs()->begin(), CE->getArgs()->end()};
ResumeArgumentLabel = "with";
break;
}
case HandlerType::INVALID:
llvm_unreachable("Invalid top handler");
}
// A vector in which each argument of Result has an entry. If the entry is
// not empty then that argument has been unwrapped using 'guard let' into
// a variable with that name.
SmallVector<Identifier, 4> ArgNames;
ArgNames.reserve(Args.size());
/// When unwrapping a result argument \p Arg into a variable using
/// 'guard let' return a suitable name for the unwrapped variable.
/// \p ArgIndex is the index of \p Arg in the results passed to the
/// completion handler.
auto GetSuitableNameForGuardUnwrap = [&](Expr *Arg,
unsigned ArgIndex) -> Identifier {
// If Arg is a DeclRef, use its name for the guard unwrap.
// guard let myVar1 = myVar.
if (auto DRE = dyn_cast<DeclRefExpr>(Arg)) {
return createUniqueName(DRE->getDecl()->getBaseIdentifier().str());
} else if (auto IIOE = dyn_cast<InjectIntoOptionalExpr>(Arg)) {
if (auto DRE = dyn_cast<DeclRefExpr>(IIOE->getSubExpr())) {
return createUniqueName(DRE->getDecl()->getBaseIdentifier().str());
}
}
if (Args.size() == 1) {
// We only have a single result. 'result' seems a resonable name.
return createUniqueName("result");
} else {
// We are returning a tuple. Name the result elements 'result' +
// index in tuple.
return createUniqueName("result" + std::to_string(ArgIndex));
}
};
unsigned ArgIndex = 0;
for (auto Arg : Args) {
auto *ArgExpr = Arg.getExpr();