This repository was archived by the owner on Apr 2, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 196
/
Copy pathSwiftASTManipulator.cpp
1340 lines (1084 loc) · 47.7 KB
/
SwiftASTManipulator.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
//===-- SwiftASTManipulator.cpp ---------------------------------*- C++ -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 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 "SwiftASTManipulator.h"
#include "lldb/Expression/ExpressionParser.h"
#include "lldb/Expression/ExpressionSourceCode.h"
#include "lldb/Target/Target.h"
#include "lldb/Utility/ConstString.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Status.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsFrontend.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeRepr.h"
#include "swift/AST/Types.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "SwiftUserExpression.h"
using namespace lldb_private;
swift::VarDecl::Specifier
SwiftASTManipulator::VariableInfo::GetVarSpecifier() const {
if (m_decl)
return m_decl->getSpecifier();
else
return m_var_specifier;
}
bool SwiftASTManipulator::VariableInfo::GetIsCaptureList() const {
if (m_decl)
return m_decl->isCaptureList();
else
return m_is_capture_list;
}
void SwiftASTManipulator::WrapExpression(
lldb_private::Stream &wrapped_stream, const char *orig_text,
uint32_t language_flags, const EvaluateExpressionOptions &options,
llvm::StringRef os_version,
uint32_t &first_body_line) {
first_body_line = 0; // set to invalid
// TODO make the extension private so we're not polluting the class
static unsigned int counter = 0;
unsigned int current_counter = counter++;
const bool playground = options.GetPlaygroundTransformEnabled();
const bool repl = options.GetREPLEnabled();
const bool generate_debug_info = options.GetGenerateDebugInfo();
const char *pound_file = options.GetPoundLineFilePath();
const uint32_t pound_line = options.GetPoundLineLine();
const char *text = orig_text;
StreamString fixed_text;
if (playground) {
const char *playground_logger_declarations = R"(
@_silgen_name ("playground_logger_initialize") func __builtin_logger_initialize ()
@_silgen_name ("playground_log_hidden") func __builtin_log_with_id<T> (_ object : T, _ name : String, _ id : Int, _ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("playground_log_scope_entry") func __builtin_log_scope_entry (_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("playground_log_scope_exit") func __builtin_log_scope_exit (_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("playground_log_postprint") func __builtin_postPrint (_ sl : Int, _ el : Int, _ sc : Int, _ ec: Int, _ moduleID: Int, _ fileID: Int) -> AnyObject
@_silgen_name ("DVTSendPlaygroundLogData") func __builtin_send_data (_ : AnyObject!)
__builtin_logger_initialize()
)";
// The debug function declarations need only be declared once per session - on the first REPL call.
// This code assumes that the first call is the first REPL call; don't call playground once then playground || repl again
bool first_expression = options.GetPreparePlaygroundStubFunctions();
const char *playground_prefix = first_expression ? playground_logger_declarations : "";
if (pound_file && pound_line) {
wrapped_stream.Printf("%s#sourceLocation(file: \"%s\", line: %u)\n%s\n",
playground_prefix, pound_file, pound_line,
orig_text);
} else {
// In 2017+, xcode playgrounds send orig_text that starts with a module loading prefix (not the above prefix), then a sourceLocation specifier that indicates the page name, and then the page body text.
// The first_body_line mechanism in this function cannot be used to compensate for the playground_prefix added here, since it incorrectly continues to apply even after sourceLocation directives are read frmo the orig_text.
// To make sure playgrounds work correctly whether or not they supply their own sourceLocation, create a dummy sourceLocation here with a fake filename that starts counting the first line of orig_text as line 1.
wrapped_stream.Printf("%s#sourceLocation(file: \"%s\", line: %u)\n%s\n",
playground_prefix, "Playground.swift", 1,
orig_text);
}
first_body_line = 1;
return;
} else if (repl) { // repl but not playground.
if (pound_file && pound_line) {
wrapped_stream.Printf("#sourceLocation(file: \"%s\", line: %u)\n%s\n",
llvm::sys::path::filename(pound_file).str().c_str(),
pound_line, orig_text);
} else {
wrapped_stream.Printf("%s", orig_text);
}
first_body_line = 1;
return;
}
std::string expr_source_path;
if (pound_file && pound_line) {
fixed_text.Printf("#sourceLocation(file: \"%s\", line: %u)\n%s\n",
pound_file, pound_line, orig_text);
text = fixed_text.GetString().data();
} else if (generate_debug_info) {
if (ExpressionSourceCode::SaveExpressionTextToTempFile(orig_text, options,
expr_source_path)) {
fixed_text.Printf("#sourceLocation(file: \"%s\", line: 1)\n%s\n",
expr_source_path.c_str(), orig_text);
text = fixed_text.GetString().data();
}
}
// Note: All the wrapper functions we make are marked with the
// @LLDBDebuggerFunction macro so that the compiler
// can do whatever special treatment it need to do on them. If you add new
// variants be sure to mark them this way.
// Also, any function that might end up being in an extension of swift class
// needs to be marked final, since otherwise
// the compiler might try to dispatch them dynamically, which it can't do
// correctly for these functions.
llvm::SmallString<32> buffer;
llvm::raw_svector_ostream os(buffer);
if (!os_version.empty())
os << "@available(" << os_version << ", *)";
std::string availability = os.str();
StreamString wrapped_expr_text;
wrapped_expr_text.Printf("do\n"
"{\n"
"%s%s%s\n" // Don't indent the code so error columns
// match up with errors from compiler
"}\n"
"catch (let __lldb_tmp_error)\n"
"{\n"
" var %s = __lldb_tmp_error\n"
"}\n",
GetUserCodeStartMarker(), text,
GetUserCodeEndMarker(), GetErrorName());
if (Flags(language_flags)
.AnySet(SwiftUserExpression::eLanguageFlagNeedsObjectPointer |
SwiftUserExpression::eLanguageFlagInStaticMethod)) {
const char *func_decorator = "";
if (language_flags & SwiftUserExpression::eLanguageFlagInStaticMethod) {
if (language_flags & SwiftUserExpression::eLanguageFlagIsClass)
func_decorator = "final class";
else
func_decorator = "static";
} else if (language_flags & SwiftUserExpression::eLanguageFlagIsClass &&
!(language_flags &
SwiftUserExpression::eLanguageFlagIsWeakSelf)) {
func_decorator = "final";
} else {
func_decorator = "mutating";
}
const char *optional_extension =
(language_flags & SwiftUserExpression::eLanguageFlagIsWeakSelf)
? "Swift.Optional where Wrapped == "
: "";
wrapped_stream.Printf(
"extension %s$__lldb_context {\n"
" @LLDBDebuggerFunction %s\n"
" %s func $__lldb_wrapped_expr_%u(_ $__lldb_arg : "
"UnsafeMutablePointer<Any>) {\n"
"%s" // This is the expression text (with newlines).
" }\n"
"}\n"
"%s\n"
"func $__lldb_expr(_ $__lldb_arg : UnsafeMutablePointer<Any>) {\n"
" do {\n"
" $__lldb_injected_self.$__lldb_wrapped_expr_%u(\n"
" $__lldb_arg\n"
" )\n"
" }\n"
"}\n",
optional_extension, availability.c_str(), func_decorator,
current_counter, wrapped_expr_text.GetData(), availability.c_str(),
current_counter);
first_body_line = 5;
} else {
wrapped_stream.Printf(
"@LLDBDebuggerFunction %s\n"
"func $__lldb_expr(_ $__lldb_arg : UnsafeMutablePointer<Any>) {\n"
"%s" // This is the expression text (with newlines).
"}\n",
availability.c_str(), wrapped_expr_text.GetData());
first_body_line = 4;
}
}
SwiftASTManipulatorBase::VariableMetadataResult::~VariableMetadataResult() {}
SwiftASTManipulatorBase::VariableMetadataError::~VariableMetadataError() {}
void SwiftASTManipulatorBase::VariableInfo::Print(
lldb_private::Stream &stream) const {
stream.Printf("[name=%s, type = ", m_name.str().str().c_str());
if (m_type.IsValid())
stream.PutCString(m_type.GetTypeName().AsCString("<no type name>"));
else
stream.PutCString("<no type>");
if (MetadataIs<VariableMetadataResult>())
stream.Printf(", is_result");
if (MetadataIs<VariableMetadataError>())
stream.Printf(", is_error");
stream.PutChar(']');
}
void SwiftASTManipulatorBase::DoInitialization() {
if (m_repl)
return;
static llvm::StringRef s_wrapped_func_prefix_str("$__lldb_wrapped_expr");
static llvm::StringRef s_func_prefix_str("$__lldb_expr");
// First pass: find whether we're dealing with a wrapped function or not
class FuncAndExtensionFinder : public swift::ASTWalker {
public:
swift::FuncDecl *m_function_decl = nullptr; // This is the function in which
// the expression code is
// inserted.
// It is always marked with the DebuggerFunction attribute.
swift::ExtensionDecl *m_extension_decl =
nullptr; // This is an optional extension holding the function
swift::FuncDecl *m_wrapper_decl = nullptr; // This is an optional wrapper
// function that calls
// m_function_decl.
llvm::StringRef m_wrapper_func_prefix; // This is the prefix name for the
// wrapper function. One tricky bit
// is that in the case where there is no wrapper, the m_function_decl
// has this name. That's why we check first for the debugger attribute.
FuncAndExtensionFinder(llvm::StringRef &wrapped_func_prefix)
: m_wrapper_func_prefix(wrapped_func_prefix) {}
bool walkToDeclPre(swift::Decl *D) override {
auto *FD = llvm::dyn_cast<swift::FuncDecl>(D);
if (!FD)
return true;
if (FD->getAttrs().hasAttribute<swift::LLDBDebuggerFunctionAttr>()) {
m_function_decl = FD;
// Now walk back up the containing DeclContexts, and if we find an
// extension Decl, that's our extension:
for (swift::DeclContext *DC = m_function_decl->getDeclContext(); DC;
DC = DC->getParent()) {
if (auto *extension_decl = llvm::dyn_cast<swift::ExtensionDecl>(DC)) {
m_extension_decl = extension_decl;
break;
}
}
} else if (FD->hasName() &&
FD->getName().str().startswith(m_wrapper_func_prefix)) {
m_wrapper_decl = FD;
}
// There's nothing buried in a function that we need to find in this
// search.
return false;
}
};
FuncAndExtensionFinder func_finder(s_func_prefix_str);
m_source_file.walk(func_finder);
m_function_decl = func_finder.m_function_decl;
m_wrapper_decl = func_finder.m_wrapper_decl;
m_extension_decl = func_finder.m_extension_decl;
assert(m_function_decl);
// Find the body in the function
if (m_function_decl) {
swift::BraceStmt *function_body = m_function_decl->getBody();
swift::DoCatchStmt *do_stmt = nullptr;
for (swift::ASTNode &element : function_body->getElements()) {
if (swift::Stmt *stmt = element.dyn_cast<swift::Stmt *>())
if ((do_stmt = llvm::dyn_cast<swift::DoCatchStmt>(stmt)))
break;
}
m_do_stmt = do_stmt;
if (do_stmt) {
// There should only be one catch:
assert(m_do_stmt->getCatches().size() == 1);
swift::CatchStmt *our_catch = m_do_stmt->getCatches().front();
if (our_catch)
m_catch_stmt = our_catch;
}
}
}
swift::BraceStmt *SwiftASTManipulatorBase::GetUserBody() {
if (!IsValid())
return nullptr;
swift::Stmt *body_stmt = m_do_stmt->getBody();
swift::BraceStmt *do_body = llvm::dyn_cast<swift::BraceStmt>(body_stmt);
return do_body;
}
SwiftASTManipulator::SwiftASTManipulator(swift::SourceFile &source_file,
bool repl)
: SwiftASTManipulatorBase(source_file, repl) {}
void SwiftASTManipulator::FindSpecialNames(
llvm::SmallVectorImpl<swift::Identifier> &names, llvm::StringRef prefix) {
names.clear();
class SpecialNameFinder : public swift::ASTWalker {
public:
typedef llvm::SmallVectorImpl<swift::Identifier> NameVector;
SpecialNameFinder(NameVector &names, llvm::StringRef &prefix)
: m_names(names), m_prefix(prefix) {}
std::pair<bool, swift::Expr *> walkToExprPre(swift::Expr *E) override {
if (auto *UDRE = llvm::dyn_cast<swift::UnresolvedDeclRefExpr>(E)) {
swift::Identifier name = UDRE->getName().getBaseIdentifier();
if (m_prefix.empty() || name.str().startswith(m_prefix))
m_names.push_back(name);
}
return {true, E};
}
private:
NameVector &m_names;
llvm::StringRef m_prefix;
};
SpecialNameFinder special_name_finder(names, prefix);
if (m_function_decl)
m_function_decl->walkContext(special_name_finder);
}
// This call replaces:
//
// <EXPR>
//
// with:
//
// do {
// var __lldb_tmp_ret_<N> = <EXPR>
// } while (false)
//
// and adds a "return" in the do-while if in_return is true.
// It records what it has done in a ResultLocationInfo, which gets pushed to the
// back of the ResultLocationInfo stack
// maintained by the SwiftASTManipulator, and returns the statement which
// effects the change.
//
// May return NULL if we can't make an appropriate variable assignment (e.g. for
// a bare "nil".)
swift::Stmt *SwiftASTManipulator::ConvertExpressionToTmpReturnVarAccess(
swift::Expr *expr, const swift::SourceLoc &source_loc, bool in_return,
swift::DeclContext *decl_context) {
// swift doesn't know how to infer the type of a variable by assignment to
// "nil". So if the
// expression is "nil" then we just drop it on the floor.
if (swift::dyn_cast<swift::NilLiteralExpr>(expr))
return nullptr;
swift::ASTContext &ast_context = m_source_file.getASTContext();
char name_buffer[64];
snprintf(name_buffer, 64, "__lldb_tmp_ret_%d", m_tmpname_idx++);
swift::Identifier name = ast_context.getIdentifier(name_buffer);
swift::Identifier equalequal_name = ast_context.getIdentifier("==");
ResultLocationInfo result_loc_info(source_loc);
result_loc_info.orig_expr = expr;
swift::DeclContext *new_decl_context = m_function_decl;
if (m_repl) {
new_decl_context = decl_context;
}
llvm::SmallVector<swift::ASTNode, 3> body;
llvm::SmallVector<swift::Expr *, 3> false_body;
const bool is_static = false;
const auto specifier = swift::VarDecl::Specifier::Var;
const bool is_capture_list = false;
result_loc_info.tmp_var_decl = new (ast_context) swift::VarDecl(
is_static, specifier, is_capture_list, source_loc, name,
new_decl_context);
result_loc_info.tmp_var_decl->setImplicit();
result_loc_info.tmp_var_decl->setAccess(
swift::AccessLevel::Internal);
result_loc_info.tmp_var_decl->setSetterAccess(
swift::AccessLevel::Internal);
swift::NamedPattern *var_pattern =
new (ast_context) swift::NamedPattern(result_loc_info.tmp_var_decl, true);
const swift::StaticSpellingKind static_spelling_kind =
swift::StaticSpellingKind::KeywordStatic;
result_loc_info.binding_decl = swift::PatternBindingDecl::createImplicit(
ast_context, static_spelling_kind, var_pattern, expr, new_decl_context);
result_loc_info.binding_decl->setStatic(false);
body.push_back(result_loc_info.binding_decl);
body.push_back(result_loc_info.tmp_var_decl);
if (in_return) {
result_loc_info.return_stmt =
new (ast_context) swift::ReturnStmt(source_loc, nullptr);
body.push_back(result_loc_info.return_stmt);
}
swift::IntegerLiteralExpr *one_expr = new (ast_context)
swift::IntegerLiteralExpr(swift::StringRef("1"), source_loc, true);
false_body.push_back(one_expr);
swift::UnresolvedDeclRefExpr *equalequal_expr = new (ast_context)
swift::UnresolvedDeclRefExpr(equalequal_name,
swift::DeclRefKind::BinaryOperator,
swift::DeclNameLoc(source_loc));
false_body.push_back(equalequal_expr);
swift::IntegerLiteralExpr *zero_expr = new (ast_context)
swift::IntegerLiteralExpr(swift::StringRef("0"), source_loc, true);
false_body.push_back(zero_expr);
swift::SequenceExpr *zero_equals_one_expr = swift::SequenceExpr::create(
ast_context, llvm::ArrayRef<swift::Expr *>(false_body));
zero_equals_one_expr->setImplicit();
swift::BraceStmt *body_stmt = swift::BraceStmt::create(
ast_context, source_loc, llvm::ArrayRef<swift::ASTNode>(body), source_loc,
true);
// Default construct a label info that contains nothing for the while
// statement
swift::LabeledStmtInfo label_info;
swift::RepeatWhileStmt *assign_stmt = new (ast_context)
swift::RepeatWhileStmt(label_info, source_loc, zero_equals_one_expr,
source_loc, body_stmt, true);
result_loc_info.wrapper_stmt = assign_stmt;
m_result_info.push_back(result_loc_info);
return assign_stmt;
}
bool SwiftASTManipulator::RewriteResult() {
class ReturnFinder : public swift::ASTWalker {
public:
ReturnFinder(SwiftASTManipulator &manipulator)
: m_manipulator(manipulator) {}
void SetDeclContext(swift::DeclContext *decl_context) {
m_decl_context = decl_context;
}
bool walkToDeclPre(swift::Decl *D) override {
switch (D->getKind()) {
default: return true;
// Don't step into function declarations, they may have returns, but we
// don't want to instrument them.
case swift::DeclKind::Func:
case swift::DeclKind::Class:
case swift::DeclKind::Struct:
return false;
}
}
std::pair<bool, swift::Expr *> walkToExprPre(swift::Expr *expr) override {
switch (expr->getKind()) {
default: return {true, expr};
// Don't step into closure definitions, they may have returns, but we
// don't want to instrument them either.
case swift::ExprKind::Closure:
return {false, expr};
}
}
swift::Stmt *walkToStmtPost(swift::Stmt *S) override {
auto *RS = swift::dyn_cast<swift::ReturnStmt>(S);
if (!RS || !RS->getResult())
return S;
if (swift::Expr *RE = RS->getResult()) {
if (swift::Stmt *S =
m_manipulator.ConvertExpressionToTmpReturnVarAccess(
RE, RS->getStartLoc(), /*add_return=*/true, m_decl_context))
return S;
}
return S;
}
private:
SwiftASTManipulator &m_manipulator;
swift::DeclContext *m_decl_context = nullptr;
};
if (!IsValid())
return false;
if (m_repl) {
ReturnFinder return_finder(*this);
// First step, walk the function body converting returns to assignments to
// temp variables + return:
for (swift::Decl *decl : m_source_file.Decls) {
if (auto top_level_code_decl =
llvm::dyn_cast<swift::TopLevelCodeDecl>(decl)) {
return_finder.SetDeclContext(top_level_code_decl);
top_level_code_decl->getBody()->walk(return_finder);
}
}
// Second step, fetch the last expression, and if it is non-null, set it to
// a temp result as well:
if (!m_source_file.Decls.empty()) {
swift::Decl *last_decl = *(m_source_file.Decls.end() - 1);
if (auto last_top_level_code_decl =
llvm::dyn_cast<swift::TopLevelCodeDecl>(last_decl)) {
llvm::MutableArrayRef<swift::ASTNode>::iterator back_iterator;
back_iterator =
last_top_level_code_decl->getBody()->getElements().end() - 1;
swift::ASTNode last_element = *back_iterator;
swift::Expr *last_expr = last_element.dyn_cast<swift::Expr *>();
if (last_expr) {
swift::Stmt *temp_result_decl = ConvertExpressionToTmpReturnVarAccess(
last_expr, last_expr->getStartLoc(), false,
last_top_level_code_decl);
if (temp_result_decl)
*back_iterator = temp_result_decl;
}
}
}
} else {
swift::BraceStmt *user_body = GetUserBody();
llvm::MutableArrayRef<swift::ASTNode> orig_elements =
user_body->getElements();
llvm::SmallVector<swift::Expr *, 1> return_values;
// The function body is wrapped in an "if (true)" when constructed, so the
// function body can not be empty
// or it was one we didn't make (or the optimizer is getting smart on us
// when it has no business doing that.)
if (orig_elements.size() == 0) {
// This is an empty expression, nothing to do here...
return true;
}
// First step, walk the function body converting returns to assignments to
// temp variables + return:
ReturnFinder return_finder(*this);
user_body->walk(return_finder);
// Second step, fetch the last expression, and if it is non-null, set it to
// a temp result as well:
llvm::MutableArrayRef<swift::ASTNode>::iterator back_iterator;
back_iterator = user_body->getElements().end() - 1;
swift::ASTNode last_element = *back_iterator;
swift::Expr *last_expr = last_element.dyn_cast<swift::Expr *>();
if (last_expr) {
swift::Stmt *temp_result_decl = ConvertExpressionToTmpReturnVarAccess(
last_expr, last_expr->getStartLoc(), false, nullptr);
if (temp_result_decl)
*back_iterator = temp_result_decl;
}
}
return true;
}
namespace {
class AssignmentMaker {
private:
llvm::SmallSet<swift::VarDecl *, 1> &m_persistent_vars;
swift::ASTContext &m_ast_context;
llvm::SmallVector<swift::ASTNode, 3> &m_elements;
llvm::SmallVectorImpl<swift::ASTNode>::iterator &m_ei;
public:
void MakeOneAssignment(swift::VarDecl *var_decl, swift::Expr *initializer,
swift::SourceLoc location) {
if (!m_persistent_vars.count(var_decl))
return;
swift::Type target_type = var_decl->getDeclContext()
->mapTypeIntoContext(var_decl->getInterfaceType());
swift::LValueType *target_lvalue_type = swift::LValueType::get(target_type);
const bool implicit = true;
const swift::AccessSemantics uses_direct_property_access =
swift::AccessSemantics::Ordinary;
swift::DeclRefExpr *decl_ref = new (m_ast_context)
swift::DeclRefExpr(var_decl, swift::DeclNameLoc(location), implicit,
uses_direct_property_access, target_lvalue_type);
swift::AssignExpr *assignment = new (m_ast_context)
swift::AssignExpr(decl_ref, location, initializer, implicit);
assignment->setType(m_ast_context.TheEmptyTupleType);
llvm::SmallVectorImpl<swift::ASTNode>::iterator next_iter = m_ei + 1;
swift::ASTNode assignment_node((swift::Expr *)assignment);
m_ei = m_elements.insert(next_iter, swift::ASTNode(assignment_node));
}
AssignmentMaker(llvm::SmallSet<swift::VarDecl *, 1> &persistent_vars,
swift::ASTContext &ast_context,
llvm::SmallVector<swift::ASTNode, 3> &elements,
llvm::SmallVectorImpl<swift::ASTNode>::iterator &ei)
: m_persistent_vars(persistent_vars), m_ast_context(ast_context),
m_elements(elements), m_ei(ei) {}
};
}
static bool hasInit(swift::PatternBindingDecl *pattern_binding) {
for (unsigned i = 0, e = pattern_binding->getNumPatternEntries(); i != e; ++i)
if (pattern_binding->getInit(i))
return true;
return false;
}
static swift::Expr *getFirstInit(swift::PatternBindingDecl *pattern_binding) {
for (unsigned i = 0, e = pattern_binding->getNumPatternEntries(); i != e; ++i)
if (pattern_binding->getInit(i))
return pattern_binding->getInit(i);
return nullptr;
}
void SwiftASTManipulator::FindVariableDeclarations(
llvm::SmallVectorImpl<size_t> &found_declarations, bool repl) {
if (!IsValid())
return;
auto register_one_var = [this,
&found_declarations](swift::VarDecl *var_decl) {
VariableInfo persistent_info;
swift::Identifier name = var_decl->getName();
size_t persistent_info_location = m_variables.size();
auto type = var_decl->getDeclContext()->mapTypeIntoContext(
var_decl->getInterfaceType());
persistent_info.m_name = name;
persistent_info.m_type = {type.getPointer()};
persistent_info.m_decl = var_decl;
m_variables.push_back(persistent_info);
found_declarations.push_back(persistent_info_location);
};
if (m_repl) {
for (swift::Decl *decl : m_source_file.Decls) {
if (swift::VarDecl *var_decl = llvm::dyn_cast<swift::VarDecl>(decl)) {
if (!var_decl->getName().str().startswith("$")) {
register_one_var(var_decl);
}
}
}
} else {
swift::BraceStmt *user_body = GetUserBody();
llvm::ArrayRef<swift::ASTNode> body_elements = user_body->getElements();
llvm::SmallVector<swift::ASTNode, 3> elements(body_elements.begin(),
body_elements.end());
for (swift::ASTNode &element : elements) {
if (swift::Decl *element_decl = element.dyn_cast<swift::Decl *>()) {
if (swift::VarDecl *var_decl =
llvm::dyn_cast<swift::VarDecl>(element_decl)) {
if (!var_decl->isDebuggerVar()) // skip bona fide external variables
// or variables we've already tagged
{
swift::Identifier name = var_decl->getName();
if (name.str().startswith("$")) {
var_decl->setDebuggerVar(true);
register_one_var(var_decl);
}
}
}
}
}
}
}
void SwiftASTManipulator::FindNonVariableDeclarations(
llvm::SmallVectorImpl<swift::ValueDecl *> &non_variables) {
if (!IsValid())
return;
if (!m_repl)
return; // we don't do this for non-REPL expressions... yet
for (swift::Decl *decl : m_source_file.Decls) {
if (swift::ValueDecl *value_decl = llvm::dyn_cast<swift::ValueDecl>(decl)) {
if (!llvm::isa<swift::VarDecl>(value_decl) && value_decl->hasName()) {
non_variables.push_back(value_decl);
}
}
}
}
void SwiftASTManipulator::InsertResult(
swift::VarDecl *result_var, swift::Type &result_type,
SwiftASTManipulator::ResultLocationInfo &result_info) {
swift::ASTContext &ast_context = m_source_file.getASTContext();
CompilerType return_ast_type(result_type.getPointer());
result_var->overwriteAccess(swift::AccessLevel::Public);
result_var->overwriteSetterAccess(swift::AccessLevel::Public);
// Finally, go reset the return expression to the new result variable for each
// of the return expressions.
// Make an LValueType of our result type for use in the assign expression.
swift::LValueType *lvalue_result = swift::LValueType::get(result_type);
// QUERY: Can I just make one of the LHS decl's and reuse it for all the
// assigns?
const swift::AccessSemantics uses_direct_property_access =
swift::AccessSemantics::Ordinary;
swift::DeclRefExpr *lhs_expr = new (ast_context)
swift::DeclRefExpr(result_var, swift::DeclNameLoc(result_info.source_loc),
true, uses_direct_property_access, lvalue_result);
swift::Expr *init_expr = getFirstInit(result_info.binding_decl);
swift::AssignExpr *assign_expr = new (ast_context)
swift::AssignExpr(lhs_expr, result_info.source_loc, init_expr, true);
assign_expr->setType(ast_context.TheEmptyTupleType);
llvm::SmallVector<swift::ASTNode, 2> new_body;
new_body.push_back(assign_expr);
if (result_info.return_stmt != nullptr)
new_body.push_back(result_info.return_stmt);
swift::BraceStmt *body_stmt = swift::BraceStmt::create(
ast_context, result_info.source_loc,
llvm::ArrayRef<swift::ASTNode>(new_body), result_info.source_loc, true);
result_info.wrapper_stmt->setBody(body_stmt);
}
void SwiftASTManipulator::InsertError(swift::VarDecl *error_var,
swift::Type &error_type) {
if (!m_do_stmt)
return;
swift::ASTContext &ast_context = m_source_file.getASTContext();
CompilerType error_ast_type(error_type.getPointer());
error_var->overwriteAccess(swift::AccessLevel::Public);
error_var->overwriteSetterAccess(swift::AccessLevel::Public);
// Finally, go reset the return expression to the new result variable for each
// of the return expressions.
// Make an LValueType of our result type for use in the assign expression.
swift::LValueType *lvalue_result = swift::LValueType::get(error_type);
// QUERY: Can I just make one of the LHS decl's and reuse it for all the
// assigns?
swift::SourceLoc error_loc = m_do_stmt->getBody()->getStartLoc();
const swift::AccessSemantics uses_direct_property_access =
swift::AccessSemantics::Ordinary;
swift::DeclRefExpr *lhs_expr = new (ast_context)
swift::DeclRefExpr(error_var, swift::DeclNameLoc(error_loc), true,
uses_direct_property_access, lvalue_result);
swift::BraceStmt *catch_body =
llvm::dyn_cast<swift::BraceStmt>(m_catch_stmt->getBody());
if (!catch_body) {
// Fixme - log this error somehow.
return;
}
llvm::ArrayRef<swift::ASTNode> body_elements = catch_body->getElements();
llvm::SmallVector<swift::ASTNode, 3> elements(body_elements.begin(),
body_elements.end());
swift::PatternBindingDecl *binding_decl = nullptr;
for (swift::ASTNode &element : elements) {
if (swift::Decl *element_decl = element.dyn_cast<swift::Decl *>()) {
binding_decl = llvm::dyn_cast<swift::PatternBindingDecl>(element_decl);
if (binding_decl)
break;
}
}
swift::Expr *init_expr = getFirstInit(binding_decl);
swift::AssignExpr *assign_expr =
new (ast_context) swift::AssignExpr(lhs_expr, error_loc, init_expr, true);
assign_expr->setType(ast_context.TheEmptyTupleType);
llvm::SmallVector<swift::ASTNode, 2> new_body;
new_body.push_back(assign_expr);
swift::BraceStmt *body_stmt = swift::BraceStmt::create(
ast_context, error_loc, llvm::ArrayRef<swift::ASTNode>(new_body),
error_loc, true);
m_catch_stmt->setBody(body_stmt);
}
bool SwiftASTManipulator::FixupResultAfterTypeChecking(Status &error) {
if (!IsValid()) {
error.SetErrorString("Operating on invalid SwiftASTManipulator");
return false;
}
// Run through the result decls and figure out the return type.
size_t num_results = m_result_info.size();
if (num_results == 0)
return true;
swift::Type result_type;
for (size_t i = 0; i < num_results; i++) {
swift::VarDecl *the_decl = m_result_info[i].tmp_var_decl;
if (the_decl->hasType()) {
swift::Type its_type = the_decl->getType();
if (result_type.isNull()) {
result_type = its_type;
} else if (!its_type.getPointer()->isEqual(result_type)) {
std::string prev_type_name = result_type.getPointer()->getString();
std::string cur_type_name = its_type.getPointer()->getString();
error.SetErrorStringWithFormat(
"Type for %zuth return value is inconsistent, previous type: %s, "
"current type: %s.",
i, prev_type_name.c_str(), cur_type_name.c_str());
return false;
}
} else {
error.SetErrorStringWithFormat(
"Type of %zuth return value could not be determined.", i);
return false;
}
}
if (result_type.isNull()) {
error.SetErrorString("Could not find the result type for this expression.");
return false;
} else if (result_type->is<swift::ErrorType>()) {
error.SetErrorString("Result type is the error type.");
return false;
}
swift::ASTContext &ast_context = m_source_file.getASTContext();
CompilerType return_ast_type(result_type.getPointer());
swift::Identifier result_var_name =
ast_context.getIdentifier(GetResultName());
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataResult());
swift::VarDecl *result_var =
AddExternalVariable(result_var_name, return_ast_type, metadata_sp);
result_var->overwriteAccess(swift::AccessLevel::Public);
result_var->overwriteSetterAccess(swift::AccessLevel::Public);
// Finally, go reset the return expression to the new result variable for each
// of the return expressions.
for (SwiftASTManipulator::ResultLocationInfo &result_info : m_result_info) {
InsertResult(result_var, result_type, result_info);
}
// Finally we have to do pretty much the same transformation on the error
// object.
// First we need to find it:
if (m_catch_stmt) {
// Search for the error variable, so we can read it and its type,
// then call InsertError to replace it with an assignment to the error
// variable.
swift::BraceStmt *catch_body =
llvm::dyn_cast<swift::BraceStmt>(m_catch_stmt->getBody());
llvm::ArrayRef<swift::ASTNode> body_elements = catch_body->getElements();
llvm::SmallVector<swift::ASTNode, 3> elements(body_elements.begin(),
body_elements.end());
for (swift::ASTNode &element : elements) {
if (swift::Decl *element_decl = element.dyn_cast<swift::Decl *>()) {
if (swift::VarDecl *var_decl =
llvm::dyn_cast<swift::VarDecl>(element_decl)) {
if (var_decl->hasType()) {
swift::Identifier error_var_name =
ast_context.getIdentifier(GetErrorName());
if (error_var_name != var_decl->getName())
continue;
swift::Type error_type = var_decl->getInterfaceType();
CompilerType error_ast_type(error_type.getPointer());
SwiftASTManipulatorBase::VariableMetadataSP error_metadata_sp(
new VariableMetadataError());
swift::VarDecl *error_var = AddExternalVariable(
error_var_name, error_ast_type, error_metadata_sp);
error_var->overwriteAccess(swift::AccessLevel::Public);
error_var->overwriteSetterAccess(
swift::AccessLevel::Public);
InsertError(error_var, error_type);
break;
}
}
}
}
}
return true;
}
swift::VarDecl *
SwiftASTManipulator::AddExternalVariable(swift::Identifier name,
CompilerType &type,
VariableMetadataSP &metadata_sp) {
if (!IsValid())
return nullptr;
VariableInfo variables[1];
variables[0].m_name = name;
variables[0].m_type = type;
variables[0].m_metadata = metadata_sp;
if (!AddExternalVariables(variables))
return nullptr;
return variables[0].m_decl;
}
static swift::PatternBindingDecl *
GetPatternBindingForVarDecl(swift::VarDecl *var_decl,
swift::DeclContext *containing_context) {
swift::ASTContext &ast_context = var_decl->getASTContext();
const bool is_implicit = true;
swift::NamedPattern *named_pattern =
new (ast_context) swift::NamedPattern(var_decl, is_implicit);
swift::Type type = containing_context->mapTypeIntoContext(
var_decl->getInterfaceType());
swift::TypedPattern *typed_pattern =
swift::TypedPattern::createImplicit(ast_context, named_pattern, type);