forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSwiftExpressionParser.cpp
1928 lines (1610 loc) · 68.5 KB
/
SwiftExpressionParser.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
//===-- SwiftExpressionParser.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 "SwiftExpressionParser.h"
#include "SwiftASTManipulator.h"
#include "SwiftExpressionSourceCode.h"
#include "SwiftREPLMaterializer.h"
#include "SwiftSILManipulator.h"
#include "SwiftUserExpression.h"
#include "Plugins/ExpressionParser/Swift/SwiftDiagnostic.h"
#include "Plugins/ExpressionParser/Swift/SwiftExpressionVariable.h"
#include "lldb/Core/Module.h"
#include "lldb/Core/ModuleList.h"
#include "lldb/Core/ModuleSpec.h"
#include "lldb/Core/ValueObject.h"
#include "lldb/Expression/DiagnosticManager.h"
#include "lldb/Expression/Expression.h"
#include "lldb/Expression/IRExecutionUnit.h"
#include "lldb/Symbol/CompileUnit.h"
#include "lldb/Symbol/SymbolFile.h"
#include "lldb/Symbol/SymbolVendor.h"
#include "lldb/Symbol/Type.h"
#include "lldb/Symbol/VariableList.h"
#include "lldb/Target/ExecutionContext.h"
#include "lldb/Target/StackFrame.h"
#include "lldb/Target/SwiftLanguageRuntime.h"
#include "lldb/Target/Target.h"
#include "lldb/Target/Thread.h"
#include "lldb/Utility/Log.h"
#include "lldb/Utility/Stream.h"
#include "llvm-c/Analysis.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "clang/Basic/Module.h"
#include "clang/Rewrite/Core/RewriteBuffer.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticConsumer.h"
#include "swift/AST/IRGenOptions.h"
#include "swift/AST/IRGenRequests.h"
#include "swift/AST/Module.h"
#include "swift/AST/ModuleLoader.h"
#include "swift/Demangling/Demangle.h"
#include "swift/Basic/PrimarySpecificPaths.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Basic/OptimizationMode.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Parse/LocalContext.h"
#include "swift/Parse/PersistentParserState.h"
#include "swift/SIL/SILDebuggerClient.h"
#include "swift/SIL/SILFunction.h"
#include "swift/SIL/SILModule.h"
#include "swift/SIL/TypeLowering.h"
#include "swift/SILOptimizer/PassManager/Passes.h"
#include "swift/Serialization/SerializedModuleLoader.h"
#include "swift/Subsystems.h"
using namespace lldb_private;
using llvm::make_error;
using llvm::StringError;
using llvm::inconvertibleErrorCode;
SwiftExpressionParser::SwiftExpressionParser(
ExecutionContextScope *exe_scope, Expression &expr,
const EvaluateExpressionOptions &options)
: ExpressionParser(exe_scope, expr, options.GetGenerateDebugInfo()),
m_expr(expr), m_triple(), m_llvm_context(), m_module(),
m_execution_unit_sp(), m_sc(), m_exe_scope(exe_scope), m_stack_frame_wp(),
m_options(options) {
assert(expr.Language() == lldb::eLanguageTypeSwift);
// TODO: This code is copied from ClangExpressionParser.cpp.
// Factor this out into common code.
lldb::TargetSP target_sp;
if (exe_scope) {
target_sp = exe_scope->CalculateTarget();
lldb::StackFrameSP stack_frame = exe_scope->CalculateStackFrame();
if (stack_frame) {
m_stack_frame_wp = stack_frame;
m_sc = stack_frame->GetSymbolContext(lldb::eSymbolContextEverything);
} else {
m_sc.target_sp = target_sp;
}
}
if (target_sp && target_sp->GetArchitecture().IsValid()) {
std::string triple = target_sp->GetArchitecture().GetTriple().str();
int dash_count = 0;
for (size_t i = 0; i < triple.size(); ++i) {
if (triple[i] == '-')
dash_count++;
if (dash_count == 3) {
triple.resize(i);
break;
}
}
m_triple = triple;
} else {
m_triple = llvm::sys::getDefaultTargetTriple();
}
if (target_sp) {
Status error;
m_swift_ast_context = std::make_unique<SwiftASTContextReader>(
target_sp->GetScratchSwiftASTContext(error, *exe_scope, true));
}
}
class VariableMetadataPersistent
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataPersistent(lldb::ExpressionVariableSP &persistent_variable_sp)
: m_persistent_variable_sp(persistent_variable_sp) {}
static constexpr unsigned Type() { return 'Pers'; }
virtual unsigned GetType() { return Type(); }
lldb::ExpressionVariableSP m_persistent_variable_sp;
};
class VariableMetadataVariable
: public SwiftASTManipulatorBase::VariableMetadata {
public:
VariableMetadataVariable(lldb::VariableSP &variable_sp)
: m_variable_sp(variable_sp) {}
static constexpr unsigned Type() { return 'Vari'; }
virtual unsigned GetType() { return Type(); }
lldb::VariableSP m_variable_sp;
};
static CompilerType ImportType(SwiftASTContextForExpressions &target_context,
CompilerType source_type) {
Status error, mangled_error;
return target_context.ImportType(source_type, error);
}
namespace {
class LLDBNameLookup : public swift::SILDebuggerClient {
public:
LLDBNameLookup(swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc, ExecutionContextScope &exe_scope)
: SILDebuggerClient(source_file.getASTContext()),
m_log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS)),
m_source_file(source_file), m_variable_map(variable_map), m_sc(sc) {
source_file.getParentModule()->setDebugClient(this);
if (!m_sc.target_sp)
return;
m_persistent_vars =
m_sc.target_sp->GetSwiftPersistentExpressionState(exe_scope);
}
virtual ~LLDBNameLookup() {}
virtual swift::SILValue emitLValueForVariable(swift::VarDecl *var,
swift::SILBuilder &builder) {
SwiftSILManipulator manipulator(builder);
swift::Identifier variable_name = var->getName();
ConstString variable_const_string(variable_name.get());
SwiftExpressionParser::SILVariableMap::iterator vi =
m_variable_map.find(variable_const_string.AsCString());
if (vi == m_variable_map.end())
return swift::SILValue();
return manipulator.emitLValueForVariable(var, vi->second);
}
SwiftPersistentExpressionState::SwiftDeclMap &GetStagedDecls() {
return m_staged_decls;
}
protected:
Log *m_log;
swift::SourceFile &m_source_file;
SwiftExpressionParser::SILVariableMap &m_variable_map;
SymbolContext m_sc;
SwiftPersistentExpressionState *m_persistent_vars = nullptr;
// Subclasses stage globalized decls in this map. They get copied
// over to the SwiftPersistentVariable store if the parse succeeds.
SwiftPersistentExpressionState::SwiftDeclMap m_staged_decls;
};
/// A name lookup class for debugger expr mode.
class LLDBExprNameLookup : public LLDBNameLookup {
public:
LLDBExprNameLookup(swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc, ExecutionContextScope &exe_scope)
: LLDBNameLookup(source_file, variable_map, sc, exe_scope) {}
virtual ~LLDBExprNameLookup() {}
virtual bool shouldGlobalize(swift::Identifier Name, swift::DeclKind Kind) {
// Extensions have to be globalized, there's no way to mark them
// as local to the function, since their name is the name of the
// thing being extended...
if (Kind == swift::DeclKind::Extension)
return true;
// Operators need to be parsed at the global scope regardless of name.
if (Kind == swift::DeclKind::Func && Name.isOperator())
return true;
const char *name_cstr = Name.get();
if (name_cstr && name_cstr[0] == '$') {
if (m_log)
m_log->Printf("[LLDBExprNameLookup::shouldGlobalize] Returning true to "
"globalizing %s",
name_cstr);
return true;
}
return false;
}
virtual void didGlobalize(swift::Decl *decl) {
swift::ValueDecl *value_decl = swift::dyn_cast<swift::ValueDecl>(decl);
if (value_decl) {
// It seems weird to be asking this again, but some DeclKinds
// must be moved to the source-file level to be legal. But we
// don't want to register them with lldb unless they are of the
// kind lldb explicitly wants to globalize.
if (shouldGlobalize(value_decl->getBaseIdentifier(),
value_decl->getKind()))
m_staged_decls.AddDecl(value_decl, false, ConstString());
}
}
virtual bool lookupOverrides(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
if (m_log) {
m_log->Printf("[LLDBExprNameLookup::lookupOverrides(%u)] Searching for %s",
count, Name.getIdentifier().get());
}
return false;
}
virtual bool lookupAdditions(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
StringRef NameStr = Name.getIdentifier().str();
if (m_log) {
m_log->Printf("[LLDBExprNameLookup::lookupAdditions (%u)] Searching for %s",
count, Name.getIdentifier().str().str().c_str());
}
ConstString name_const_str(NameStr);
std::vector<swift::ValueDecl *> results;
// First look up the matching decls we've made in this compile.
// Later, when we look for persistent decls, these staged decls
// take precedence.
m_staged_decls.FindMatchingDecls(name_const_str, {}, results);
// Next look up persistent decls matching this name. Then, if we
// aren't looking at a debugger variable, filter out persistent
// results of the same kind as one found by the ordinary lookup
// mechanism in the parser. The problem we are addressing here is
// the case where the user has entered the REPL while in an
// ordinary debugging session to play around. While there, e.g.,
// they define a class that happens to have the same name as one
// in the program, then in some other context "expr" will call the
// class they've defined, not the one in the program itself would
// use. Plain "expr" should behave as much like code in the
// program would, so we want to favor entities of the same
// DeclKind & name from the program over ones defined in the REPL.
// For function decls we check the interface type and full name so
// we don't remove overloads that don't exist in the current
// scope.
//
// Note also, we only do this for the persistent decls. Anything
// in the "staged" list has been defined in this expr setting and
// so is more local than local.
if (m_persistent_vars) {
bool is_debugger_variable = !NameStr.empty() && NameStr.front() == '$';
size_t num_external_results = RV.size();
if (!is_debugger_variable && num_external_results > 0) {
std::vector<swift::ValueDecl *> persistent_results;
m_persistent_vars->GetSwiftPersistentDecls(name_const_str, {},
persistent_results);
size_t num_persistent_results = persistent_results.size();
for (size_t idx = 0; idx < num_persistent_results; idx++) {
swift::ValueDecl *value_decl = persistent_results[idx];
if (!value_decl)
continue;
swift::DeclName value_decl_name = value_decl->getName();
swift::DeclKind value_decl_kind = value_decl->getKind();
swift::CanType value_interface_type =
value_decl->getInterfaceType()->getCanonicalType();
bool is_function =
swift::isa<swift::AbstractFunctionDecl>(value_decl);
bool skip_it = false;
for (size_t rv_idx = 0; rv_idx < num_external_results; rv_idx++) {
if (swift::ValueDecl *rv_decl = RV[rv_idx].getValueDecl()) {
if (value_decl_kind == rv_decl->getKind()) {
if (is_function) {
swift::DeclName rv_full_name = rv_decl->getName();
if (rv_full_name.matchesRef(value_decl_name)) {
// If the full names match, make sure the
// interface types match:
if (rv_decl->getInterfaceType()->getCanonicalType() ==
value_interface_type)
skip_it = true;
}
} else {
skip_it = true;
}
if (skip_it)
break;
}
}
}
if (!skip_it)
results.push_back(value_decl);
}
} else {
m_persistent_vars->GetSwiftPersistentDecls(name_const_str, results,
results);
}
}
for (size_t idx = 0; idx < results.size(); idx++) {
swift::ValueDecl *value_decl = results[idx];
// No import required.
assert(&DC->getASTContext() == &value_decl->getASTContext());
RV.push_back(swift::LookupResultEntry(value_decl));
}
return results.size() > 0;
}
virtual swift::Identifier getPreferredPrivateDiscriminator() {
if (m_sc.comp_unit) {
if (lldb_private::Module *module = m_sc.module_sp.get()) {
if (lldb_private::SymbolFile *symbol_file =
module->GetSymbolFile()) {
std::string private_discriminator_string;
if (symbol_file->GetCompileOption("-private-discriminator",
private_discriminator_string,
m_sc.comp_unit)) {
return m_source_file.getASTContext().getIdentifier(
private_discriminator_string);
}
}
}
}
return swift::Identifier();
}
};
/// A name lookup class for REPL and Playground mode.
class LLDBREPLNameLookup : public LLDBNameLookup {
public:
LLDBREPLNameLookup(swift::SourceFile &source_file,
SwiftExpressionParser::SILVariableMap &variable_map,
SymbolContext &sc, ExecutionContextScope &exe_scope)
: LLDBNameLookup(source_file, variable_map, sc, exe_scope) {}
virtual ~LLDBREPLNameLookup() {}
virtual bool shouldGlobalize(swift::Identifier Name, swift::DeclKind kind) {
return false;
}
virtual void didGlobalize (swift::Decl *Decl) {}
virtual bool lookupOverrides(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
return false;
}
virtual bool lookupAdditions(swift::DeclBaseName Name, swift::DeclContext *DC,
swift::SourceLoc Loc, bool IsTypeLookup,
ResultVector &RV) {
static unsigned counter = 0;
unsigned count = counter++;
StringRef NameStr = Name.getIdentifier().str();
ConstString name_const_str(NameStr);
if (m_log) {
m_log->Printf("[LLDBREPLNameLookup::lookupAdditions (%u)] Searching for %s",
count, Name.getIdentifier().str().str().c_str());
}
// Find decls that come from the current compilation.
std::vector<swift::ValueDecl *> current_compilation_results;
for (auto result : RV) {
auto result_decl = result.getValueDecl();
auto result_decl_context = result_decl->getDeclContext();
if (result_decl_context->isChildContextOf(DC) || result_decl_context == DC)
current_compilation_results.push_back(result_decl);
}
// Find persistent decls, excluding decls that are equivalent to
// decls from the current compilation. This makes the decls from
// the current compilation take precedence.
std::vector<swift::ValueDecl *> persistent_decl_results;
m_persistent_vars->GetSwiftPersistentDecls(name_const_str,
current_compilation_results,
persistent_decl_results);
// Append the persistent decls that we found to the result vector.
for (auto result : persistent_decl_results) {
// No import required.
assert(&DC->getASTContext() == &result->getASTContext());
RV.push_back(swift::LookupResultEntry(result));
}
return !persistent_decl_results.empty();
}
virtual swift::Identifier getPreferredPrivateDiscriminator() {
return swift::Identifier();
}
};
}; // END Anonymous namespace
static void
AddRequiredAliases(Block *block, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContextForExpressions &swift_ast_context,
SwiftASTManipulator &manipulator) {
// First emit the typealias for "$__lldb_context".
if (!block)
return;
Function *function = block->CalculateSymbolContextFunction();
if (!function)
return;
constexpr bool can_create = true;
Block &function_block(function->GetBlock(can_create));
lldb::VariableListSP variable_list_sp(
function_block.GetBlockVariableList(true));
if (!variable_list_sp)
return;
lldb::VariableSP self_var_sp(
variable_list_sp->FindVariable(ConstString("self")));
if (!self_var_sp)
return;
CompilerType self_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(self_var_sp,
lldb::eNoDynamicValues);
if (valobj_sp)
self_type = valobj_sp->GetCompilerType();
}
if (!self_type.IsValid()) {
if (Type *type = self_var_sp->GetType()) {
self_type = type->GetForwardCompilerType();
}
}
if (!self_type.IsValid() ||
!self_type.GetTypeSystem()->SupportsLanguage(lldb::eLanguageTypeSwift))
return;
// Import before getting the unbound version, because the unbound
// version may not be in the mangled name map.
CompilerType imported_self_type = ImportType(swift_ast_context, self_type);
if (!imported_self_type.IsValid())
return;
auto *swift_runtime =
SwiftLanguageRuntime::Get(stack_frame_sp->GetThread()->GetProcess());
auto *stack_frame = stack_frame_sp.get();
imported_self_type =
swift_runtime->DoArchetypeBindingForType(*stack_frame,
imported_self_type);
// This might be a referenced type, in which case we really want to
// extend the referent:
imported_self_type =
llvm::cast<TypeSystemSwift>(imported_self_type.GetTypeSystem())
->GetReferentType(imported_self_type);
// If we are extending a generic class it's going to be a metatype,
// and we have to grab the instance type:
imported_self_type =
llvm::cast<TypeSystemSwift>(imported_self_type.GetTypeSystem())
->GetInstanceType(imported_self_type.GetOpaqueQualType());
Flags imported_self_type_flags(imported_self_type.GetTypeInfo());
swift::Type object_type =
GetSwiftType(imported_self_type)->getWithoutSpecifierType();
if (object_type.getPointer() &&
(object_type.getPointer() != imported_self_type.GetOpaqueQualType()))
imported_self_type = ToCompilerType(object_type.getPointer());
// If 'self' is a weak storage type, it must be an optional. Look
// through it and unpack the argument of "optional".
if (swift::WeakStorageType *weak_storage_type =
GetSwiftType(imported_self_type)->getAs<swift::WeakStorageType>()) {
swift::Type referent_type = weak_storage_type->getReferentType();
swift::BoundGenericEnumType *optional_type =
referent_type->getAs<swift::BoundGenericEnumType>();
if (!optional_type)
return;
swift::Type first_arg_type = optional_type->getGenericArgs()[0];
swift::ClassType *self_class_type =
first_arg_type->getAs<swift::ClassType>();
if (!self_class_type)
return;
imported_self_type = ToCompilerType(self_class_type);
}
imported_self_type_flags.Reset(imported_self_type.GetTypeInfo());
if (imported_self_type_flags.AllClear(lldb::eTypeIsGenericTypeParam)) {
swift::ValueDecl *type_alias_decl = nullptr;
type_alias_decl = manipulator.MakeGlobalTypealias(
swift_ast_context.GetASTContext()->getIdentifier("$__lldb_context"),
imported_self_type);
if (!type_alias_decl) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to make the "
"$__lldb_context typealias.");
}
} else {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (log)
log->Printf("SEP:AddRequiredAliases: Failed to resolve the self "
"archetype - could not make the $__lldb_context "
"typealias.");
}
}
/// Create a \c VariableInfo record for \c variable if there isn't
/// already shadowing inner declaration in \c processed_variables.
static void AddVariableInfo(
lldb::VariableSP variable_sp, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContextForExpressions &ast_context,
SwiftLanguageRuntime *language_runtime,
llvm::SmallDenseSet<const char *, 8> &processed_variables,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
StringRef name = variable_sp->GetUnqualifiedName().GetStringRef();
const char *name_cstr = name.data();
assert(StringRef(name_cstr) == name && "missing null terminator");
if (name.empty())
return;
// To support "guard let self = self" the function argument "self"
// is processed (as the special self argument) even if it is
// shadowed by a local variable.
bool is_self = SwiftLanguageRuntime::IsSelf(*variable_sp);
const char *overridden_name = name_cstr;
if (is_self)
overridden_name = "$__lldb_injected_self";
if (processed_variables.count(overridden_name))
return;
CompilerType var_type;
if (stack_frame_sp) {
lldb::ValueObjectSP valobj_sp =
stack_frame_sp->GetValueObjectForFrameVariable(variable_sp,
lldb::eNoDynamicValues);
if (!valobj_sp || valobj_sp->GetError().Fail()) {
// Ignore the variable if we couldn't find its corresponding
// value object. TODO if the expression tries to use an
// ignored variable, produce a sensible error.
return;
}
var_type = valobj_sp->GetCompilerType();
}
if (!var_type.IsValid())
if (Type *var_lldb_type = variable_sp->GetType())
var_type = var_lldb_type->GetFullCompilerType();
if (!var_type.IsValid())
return;
if (!var_type.GetTypeSystem()->SupportsLanguage(lldb::eLanguageTypeSwift))
return;
Status error;
CompilerType target_type = ast_context.ImportType(var_type, error);
// If the import failed, give up.
if (!target_type.IsValid())
return;
// Resolve all archetypes in the variable type.
if (stack_frame_sp)
if (language_runtime)
target_type = language_runtime->DoArchetypeBindingForType(*stack_frame_sp,
target_type);
// If we couldn't fully realize the type, then we aren't going
// to get very far making a local out of it, so discard it here.
Log *log(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TYPES |
LIBLLDB_LOG_EXPRESSIONS));
if (!SwiftASTContext::IsFullyRealized(target_type)) {
if (log)
log->Printf("Discarding local %s because we couldn't fully realize it, "
"our best attempt was: %s.",
name_cstr, target_type.GetTypeName().AsCString("<unknown>"));
return;
}
if (log && is_self)
if (swift::Type swift_type = GetSwiftType(target_type)) {
std::string s;
llvm::raw_string_ostream ss(s);
swift_type->dump(ss);
ss.flush();
log->Printf("Adding injected self: type (%p) context(%p) is: %s",
static_cast<void *>(swift_type.getPointer()),
static_cast<void *>(ast_context.GetASTContext()), s.c_str());
}
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataVariable(variable_sp));
SwiftASTManipulator::VariableInfo variable_info(
target_type, ast_context.GetASTContext()->getIdentifier(overridden_name),
metadata_sp,
variable_sp->IsConstant() ? swift::VarDecl::Introducer::Let
: swift::VarDecl::Introducer::Var);
local_variables.push_back(variable_info);
processed_variables.insert(overridden_name);
}
/// Create a \c VariableInfo record for each visible variable.
static void RegisterAllVariables(
SymbolContext &sc, lldb::StackFrameSP &stack_frame_sp,
SwiftASTContextForExpressions &ast_context,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
if (!sc.block && !sc.function)
return;
Block *block = sc.block;
Block *top_block = block->GetContainingInlinedBlock();
if (!top_block)
top_block = &sc.function->GetBlock(true);
SwiftLanguageRuntime *language_runtime = nullptr;
ExecutionContextScope *scope = nullptr;
if (stack_frame_sp) {
language_runtime =
SwiftLanguageRuntime::Get(stack_frame_sp->GetThread()->GetProcess());
scope = stack_frame_sp.get();
}
// The module scoped variables are stored at the CompUnit level, so
// after we go through the current context, then we have to take one
// more pass through the variables in the CompUnit.
VariableList variables;
// Proceed from the innermost scope outwards, adding all variables
// not already shadowed by an inner declaration.
llvm::SmallDenseSet<const char *, 8> processed_names;
bool done = false;
do {
// Iterate over all parent contexts *including* the top_block.
if (block == top_block)
done = true;
bool can_create = true;
bool get_parent_variables = false;
bool stop_if_block_is_inlined_function = true;
block->AppendVariables(
can_create, get_parent_variables, stop_if_block_is_inlined_function,
[](Variable *) { return true; }, &variables);
if (!done)
block = block->GetParent();
} while (block && !done);
// Also add local copies of globals. This is in many cases redundant
// work because the globals would also be found in the expression
// context's Swift module, but it allows a limited form of
// expression evaluation to work even if the Swift module failed to
// load, as long as the module isn't necessary to resolve the type
// or aother symbols in the expression.
if (sc.comp_unit) {
lldb::VariableListSP globals_sp = sc.comp_unit->GetVariableList(true);
if (globals_sp)
variables.AddVariables(globals_sp.get());
}
for (size_t vi = 0, ve = variables.GetSize(); vi != ve; ++vi)
AddVariableInfo({variables.GetVariableAtIndex(vi)}, stack_frame_sp,
ast_context, language_runtime, processed_names,
local_variables);
}
static void ResolveSpecialNames(
SymbolContext &sc, ExecutionContextScope &exe_scope,
SwiftASTContextForExpressions &ast_context,
llvm::SmallVectorImpl<swift::Identifier> &special_names,
llvm::SmallVectorImpl<SwiftASTManipulator::VariableInfo> &local_variables) {
Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS));
if (!sc.target_sp)
return;
auto *persistent_state =
sc.target_sp->GetSwiftPersistentExpressionState(exe_scope);
std::set<ConstString> resolved_names;
for (swift::Identifier &name : special_names) {
ConstString name_cs = ConstString(name.str());
if (resolved_names.count(name_cs))
continue;
resolved_names.insert(name_cs);
if (log)
log->Printf("Resolving special name %s", name_cs.AsCString());
lldb::ExpressionVariableSP expr_var_sp =
persistent_state->GetVariable(name_cs);
if (!expr_var_sp)
continue;
CompilerType var_type = expr_var_sp->GetCompilerType();
if (!var_type.IsValid())
continue;
if (!var_type.GetTypeSystem()->SupportsLanguage(lldb::eLanguageTypeSwift))
continue;
CompilerType target_type;
Status error;
target_type = ast_context.ImportType(var_type, error);
if (!target_type)
continue;
SwiftASTManipulatorBase::VariableMetadataSP metadata_sp(
new VariableMetadataPersistent(expr_var_sp));
auto introducer = llvm::cast<SwiftExpressionVariable>(expr_var_sp.get())
->GetIsModifiable()
? swift::VarDecl::Introducer::Var
: swift::VarDecl::Introducer::Let;
SwiftASTManipulator::VariableInfo variable_info(
target_type, ast_context.GetASTContext()->getIdentifier(name.str()),
metadata_sp, introducer);
local_variables.push_back(variable_info);
}
}
/// Initialize the SwiftASTContext and return the wrapped
/// swift::ASTContext when successful.
static swift::ASTContext *
SetupASTContext(SwiftASTContextForExpressions *swift_ast_context,
DiagnosticManager &diagnostic_manager,
std::function<bool()> disable_objc_runtime, bool repl,
bool playground) {
if (!swift_ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"No AST context to parse into. Please parse with a target.\n");
return nullptr;
}
// Lazily get the clang importer if we can to make sure it exists in
// case we need it.
if (!swift_ast_context->GetClangImporter()) {
std::string swift_error =
swift_ast_context->GetFatalErrors().AsCString("error: unknown error.");
diagnostic_manager.PutString(eDiagnosticSeverityError, swift_error);
diagnostic_manager.PutString(eDiagnosticSeverityRemark,
"Couldn't initialize Swift expression "
"evaluator due to previous errors.");
return nullptr;
}
if (swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return nullptr;
}
swift::ASTContext *ast_context = swift_ast_context->GetASTContext();
if (!ast_context) {
diagnostic_manager.PutString(
eDiagnosticSeverityError,
"Couldn't initialize the AST context. Please check your settings.");
return nullptr;
}
if (swift_ast_context->HasFatalErrors()) {
diagnostic_manager.PutString(eDiagnosticSeverityError,
"The AST context is in a fatal error state.");
return nullptr;
}
// TODO: Find a way to get contraint-solver output sent to a stream
// so we can log it.
// swift_ast_context->GetLanguageOptions().DebugConstraintSolver = true;
swift_ast_context->ClearDiagnostics();
swift_ast_context->GetLanguageOptions().DebuggerSupport = true;
// No longer part of debugger support, set it separately.
swift_ast_context->GetLanguageOptions().EnableDollarIdentifiers = true;
swift_ast_context->GetLanguageOptions().EnableAccessControl =
(repl || playground);
swift_ast_context->GetLanguageOptions().EnableTargetOSChecking = false;
if (disable_objc_runtime())
swift_ast_context->GetLanguageOptions().EnableObjCInterop = false;
swift_ast_context->GetLanguageOptions().Playground = repl || playground;
swift_ast_context->GetIRGenOptions().Playground = repl || playground;
// For the expression parser and REPL we want to relax the
// requirement that you put "try" in front of every expression that
// might throw.
if (repl || !playground)
swift_ast_context->GetLanguageOptions().EnableThrowWithoutTry = true;
swift_ast_context->GetIRGenOptions().OutputKind =
swift::IRGenOutputKind::Module;
swift_ast_context->GetIRGenOptions().OptMode =
swift::OptimizationMode::NoOptimization;
// Normally we'd like to verify, but unfortunately the verifier's
// error mode is abort().
swift_ast_context->GetIRGenOptions().Verify = false;
swift_ast_context->GetIRGenOptions().ForcePublicLinkage = true;
swift_ast_context->GetIRGenOptions().DisableRoundTripDebugTypes = true;
return ast_context;
}
/// Returns the buffer_id for the expression's source code.
static std::pair<unsigned, std::string>
CreateMainFile(SwiftASTContextForExpressions &swift_ast_context,
StringRef filename, StringRef text,
const EvaluateExpressionOptions &options) {
const bool generate_debug_info = options.GetGenerateDebugInfo();
swift_ast_context.SetGenerateDebugInfo(generate_debug_info
? swift::IRGenDebugInfoLevel::Normal
: swift::IRGenDebugInfoLevel::None);
swift::IRGenOptions &ir_gen_options = swift_ast_context.GetIRGenOptions();
if (generate_debug_info) {
std::string temp_source_path;
if (SwiftASTManipulator::SaveExpressionTextToTempFile(text, options, temp_source_path)) {
auto error_or_buffer_ap =
llvm::MemoryBuffer::getFile(temp_source_path.c_str());
if (error_or_buffer_ap.getError() == std::error_condition()) {
unsigned buffer_id =
swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(error_or_buffer_ap.get()));
llvm::SmallString<256> source_dir(temp_source_path);
llvm::sys::path::remove_filename(source_dir);
ir_gen_options.DebugCompilationDir = source_dir.str();
return {buffer_id, temp_source_path};
}
}
}
std::unique_ptr<llvm::MemoryBuffer> expr_buffer(
llvm::MemoryBuffer::getMemBufferCopy(text, filename));
unsigned buffer_id = swift_ast_context.GetSourceManager().addNewSourceBuffer(
std::move(expr_buffer));
return {buffer_id, filename};
}
/// Attempt to materialize one variable.
static llvm::Optional<SwiftExpressionParser::SILVariableInfo>
MaterializeVariable(SwiftASTManipulatorBase::VariableInfo &variable,
SwiftUserExpression &user_expression,
Materializer &materializer,
SwiftASTManipulator &manipulator,
lldb::StackFrameWP &stack_frame_wp,
DiagnosticManager &diagnostic_manager, Log *log,
bool repl) {
uint64_t offset = 0;
bool needs_init = false;
bool is_result =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataResult>();
bool is_error =
variable.MetadataIs<SwiftASTManipulatorBase::VariableMetadataError>();
if (is_result || is_error) {
needs_init = true;
Status error;
if (repl) {
if (swift::Type swift_type = GetSwiftType(variable.GetType())) {
if (!swift_type->isVoid()) {
auto &repl_mat = *llvm::cast<SwiftREPLMaterializer>(&materializer);
if (is_result)
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetResultDelegate(), error);
else
offset = repl_mat.AddREPLResultVariable(
variable.GetType(), variable.GetDecl(),
&user_expression.GetErrorDelegate(), error);
}
}
} else {
CompilerType actual_type(variable.GetType());
auto orig_swift_type = GetSwiftType(actual_type);
auto *swift_type = orig_swift_type->mapTypeOutOfContext().getPointer();
actual_type = ToCompilerType(swift_type);
lldb::StackFrameSP stack_frame_sp = stack_frame_wp.lock();
if (swift_type->hasTypeParameter()) {
if (stack_frame_sp && stack_frame_sp->GetThread() &&
stack_frame_sp->GetThread()->GetProcess()) {
auto *swift_runtime = SwiftLanguageRuntime::Get(
stack_frame_sp->GetThread()->GetProcess());
if (swift_runtime) {
actual_type = swift_runtime->DoArchetypeBindingForType(
*stack_frame_sp, actual_type);
}
}
}
// Desugar '$lldb_context', etc.
auto transformed_type = GetSwiftType(actual_type).transform(
[](swift::Type t) -> swift::Type {
if (auto *aliasTy = swift::dyn_cast<swift::TypeAliasType>(t.getPointer())) {