-
Notifications
You must be signed in to change notification settings - Fork 10.2k
/
Requests.cpp
4267 lines (3695 loc) · 153 KB
/
Requests.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
//===--- Requests.cpp -----------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 "sourcekitd/Service.h"
#include "sourcekitd/CodeCompletionResultsArray.h"
#include "sourcekitd/DictionaryKeys.h"
#include "sourcekitd/DocStructureArray.h"
#include "sourcekitd/DocSupportAnnotationArray.h"
#include "sourcekitd/TokenAnnotationsArray.h"
#include "sourcekitd/ExpressionTypeArray.h"
#include "sourcekitd/VariableTypeArray.h"
#include "SourceKit/Core/Context.h"
#include "SourceKit/Core/LangSupport.h"
#include "SourceKit/Core/NotificationCenter.h"
#include "SourceKit/Support/CancellationToken.h"
#include "SourceKit/Support/Concurrency.h"
#include "SourceKit/Support/Logging.h"
#include "SourceKit/Support/Statistic.h"
#include "SourceKit/Support/Tracing.h"
#include "SourceKit/Support/UIdent.h"
#include "SourceKit/SwiftLang/Factory.h"
#include "swift/Basic/InitializeSwiftModules.h"
#include "swift/Basic/LLVMInitialize.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/Version.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/Support/MemoryBuffer.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/VirtualFileSystem.h"
#include "llvm/Support/raw_ostream.h"
#include <mutex>
// FIXME: Portability.
#include <dispatch/dispatch.h>
using namespace sourcekitd;
using namespace SourceKit;
namespace {
class LazySKDUID {
const char *Name;
mutable std::atomic<sourcekitd_uid_t> UID { nullptr };
public:
LazySKDUID(const char *Name) : Name(Name) { }
sourcekitd_uid_t get() const {
sourcekitd_uid_t UIDValue = UID;
if (!UIDValue)
UID = SKDUIDFromUIdent(UIdent(Name));
return UID;
}
operator sourcekitd_uid_t() const {
return get();
}
StringRef str() const {
return StringRef(Name);
}
};
struct SKEditorConsumerOptions {
bool EnableSyntaxMap = false;
bool EnableStructure = false;
bool EnableDiagnostics = false;
bool SyntacticOnly = false;
};
} // anonymous namespace
static Optional<UIdent> getUIDForOperationKind(trace::OperationKind OpKind);
static void fillDiagnosticInfo(ResponseBuilder::Dictionary ParentElem,
ArrayRef<DiagnosticEntryInfo> Diags,
Optional<UIdent> DiagStage);
#define REQUEST(NAME, CONTENT) static LazySKDUID Request##NAME(CONTENT);
#define KIND(NAME, CONTENT) static LazySKDUID Kind##NAME(CONTENT);
#include "SourceKit/Core/ProtocolUIDs.def"
#define REFACTORING(KIND, NAME, ID) static LazySKDUID Kind##Refactoring##KIND("source.refactoring.kind."#ID);
#include "swift/Refactoring/RefactoringKinds.def"
static SourceKit::Context *GlobalCtx = nullptr;
// NOTE: if we had a connection context, these stats should move into it.
static Statistic numRequests(UIdentFromSKDUID(KindStatNumRequests),
"# of requests (total)");
static Statistic numSemaRequests(UIdentFromSKDUID(KindStatNumSemaRequests),
"# of semantic requests");
void sourcekitd::initializeService(
llvm::StringRef swiftExecutablePath, StringRef runtimeLibPath,
StringRef diagnosticDocumentationPath,
std::function<void(sourcekitd_response_t)> postNotification) {
INITIALIZE_LLVM();
initializeSwiftModules();
llvm::EnablePrettyStackTrace();
GlobalCtx = new SourceKit::Context(swiftExecutablePath, runtimeLibPath,
diagnosticDocumentationPath,
SourceKit::createSwiftLangSupport);
auto noteCenter = GlobalCtx->getNotificationCenter();
noteCenter->addDocumentUpdateNotificationReceiver([postNotification](StringRef DocumentName) {
static UIdent DocumentUpdateNotificationUID(
"source.notification.editor.documentupdate");
ResponseBuilder RespBuilder;
auto Dict = RespBuilder.getDictionary();
Dict.set(KeyNotification, DocumentUpdateNotificationUID);
Dict.set(KeyName, DocumentName);
postNotification(RespBuilder.createResponse());
});
noteCenter->addTestNotificationReceiver([postNotification] {
static UIdent TestNotification("source.notification.test");
ResponseBuilder RespBuilder;
auto Dict = RespBuilder.getDictionary();
Dict.set(KeyNotification, TestNotification);
postNotification(RespBuilder.createResponse());
});
noteCenter->addSemaEnabledNotificationReceiver([postNotification] {
static UIdent SemaEnabledNotificationUID(
"source.notification.sema_enabled");
ResponseBuilder RespBuilder;
auto Dict = RespBuilder.getDictionary();
Dict.set(KeyNotification, SemaEnabledNotificationUID);
postNotification(RespBuilder.createResponse());
});
noteCenter->addCompileWillStartNotificationReceiver([postNotification](uint64_t OpId, trace::OperationKind OpKind, const trace::SwiftInvocation &Inv){
static UIdent CompileWillStartUID("source.notification.compile-will-start");
ResponseBuilder RespBuilder;
auto Dict = RespBuilder.getDictionary();
Dict.set(KeyNotification, CompileWillStartUID);
Dict.set(KeyCompileID, std::to_string(OpId));
Dict.set(KeyFilePath, Inv.Args.PrimaryFile);
if (auto OperationUID = getUIDForOperationKind(OpKind))
Dict.set(KeyCompileOperation, OperationUID.value());
Dict.set(KeyCompilerArgsString, Inv.Args.Arguments);
postNotification(RespBuilder.createResponse());
});
noteCenter->addCompileDidFinishNotificationReceiver([postNotification](uint64_t OpId, trace::OperationKind OpKind, ArrayRef<DiagnosticEntryInfo> Diagnostics){
static UIdent CompileDidFinishUID("source.notification.compile-did-finish");
ResponseBuilder RespBuilder;
auto Dict = RespBuilder.getDictionary();
Dict.set(KeyNotification, CompileDidFinishUID);
Dict.set(KeyCompileID, std::to_string(OpId));
if (auto OperationUID = getUIDForOperationKind(OpKind))
Dict.set(KeyCompileOperation, OperationUID.value());
fillDiagnosticInfo(Dict, Diagnostics, /*DiagStage*/ None);
postNotification(RespBuilder.createResponse());
});
}
void sourcekitd::shutdownService() {
delete GlobalCtx;
GlobalCtx = nullptr;
}
static SourceKit::Context &getGlobalContext() {
assert(GlobalCtx);
return *GlobalCtx;
}
static sourcekitd_response_t indexSource(StringRef Filename,
ArrayRef<const char *> Args);
static sourcekitd_response_t reportDocInfo(llvm::MemoryBuffer *InputBuf,
StringRef ModuleName,
ArrayRef<const char *> Args);
static void reportCursorInfo(const RequestResult<CursorInfoData> &Result, ResponseReceiver Rec);
static void reportDiagnostics(const RequestResult<DiagnosticsResult> &Result,
ResponseReceiver Rec);
static void reportExpressionTypeInfo(const RequestResult<ExpressionTypesInFile> &Result,
ResponseReceiver Rec);
static void
reportVariableTypeInfo(const RequestResult<VariableTypesInFile> &Result,
ResponseReceiver Rec);
static void reportRangeInfo(const RequestResult<RangeInfo> &Result, ResponseReceiver Rec);
static void reportNameInfo(const RequestResult<NameTranslatingInfo> &Result, ResponseReceiver Rec);
static void findRelatedIdents(StringRef PrimaryFilePath,
StringRef InputBufferName, int64_t Offset,
bool CancelOnSubsequentRequest,
ArrayRef<const char *> Args,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec);
static void findActiveRegions(StringRef PrimaryFilePath,
StringRef InputBufferName,
ArrayRef<const char *> Args,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec);
static sourcekitd_response_t
codeComplete(llvm::MemoryBuffer *InputBuf, int64_t Offset,
Optional<RequestDict> optionsDict, ArrayRef<const char *> Args,
Optional<VFSOptions> vfsOptions,
SourceKitCancellationToken CancellationToken);
static sourcekitd_response_t
codeCompleteOpen(StringRef name, llvm::MemoryBuffer *InputBuf, int64_t Offset,
Optional<RequestDict> optionsDict, ArrayRef<const char *> Args,
Optional<VFSOptions> vfsOptions,
SourceKitCancellationToken CancellationToken);
static sourcekitd_response_t
codeCompleteUpdate(StringRef name, int64_t Offset,
Optional<RequestDict> optionsDict,
SourceKitCancellationToken CancellationToken);
static sourcekitd_response_t codeCompleteClose(StringRef name, int64_t Offset);
static sourcekitd_response_t
typeContextInfo(llvm::MemoryBuffer *InputBuf, int64_t Offset,
Optional<RequestDict> optionsDict, ArrayRef<const char *> Args,
Optional<VFSOptions> vfsOptions,
SourceKitCancellationToken CancellationToken);
static sourcekitd_response_t conformingMethodList(
llvm::MemoryBuffer *InputBuf, int64_t Offset,
Optional<RequestDict> optionsDict, ArrayRef<const char *> Args,
ArrayRef<const char *> ExpectedTypes, Optional<VFSOptions> vfsOptions,
SourceKitCancellationToken CancellationToken);
static sourcekitd_response_t
editorOpen(StringRef Name, llvm::MemoryBuffer *Buf,
SKEditorConsumerOptions Opts, ArrayRef<const char *> Args,
Optional<VFSOptions> vfsOptions);
static sourcekitd_response_t
editorOpenInterface(StringRef Name, StringRef ModuleName,
Optional<StringRef> Group, ArrayRef<const char *> Args,
bool SynthesizedExtensions,
Optional<StringRef> InterestedUSR);
static sourcekitd_response_t
editorOpenHeaderInterface(StringRef Name, StringRef HeaderName,
ArrayRef<const char *> Args,
bool UsingSwiftArgs,
bool SynthesizedExtensions,
StringRef swiftVersion);
static void editorOpenSwiftSourceInterface(
StringRef Name, StringRef SourceName, ArrayRef<const char *> Args,
SourceKitCancellationToken CancellationToken, ResponseReceiver Rec);
static void
editorOpenSwiftTypeInterface(StringRef TypeUsr, ArrayRef<const char *> Args,
ResponseReceiver Rec);
static sourcekitd_response_t editorExtractTextFromComment(StringRef Source);
static sourcekitd_response_t editorConvertMarkupToXML(StringRef Source);
static sourcekitd_response_t
editorClose(StringRef Name, bool RemoveCache);
static sourcekitd_response_t
editorReplaceText(StringRef Name, llvm::MemoryBuffer *Buf, unsigned Offset,
unsigned Length, SKEditorConsumerOptions Opts);
static void
editorApplyFormatOptions(StringRef Name, RequestDict &FmtOptions);
static sourcekitd_response_t
editorFormatText(StringRef Name, unsigned Line, unsigned Length);
static sourcekitd_response_t
editorExpandPlaceholder(StringRef Name, unsigned Offset, unsigned Length);
static sourcekitd_response_t
editorFindUSR(StringRef DocumentName, StringRef USR);
static sourcekitd_response_t
editorFindInterfaceDoc(StringRef ModuleName, ArrayRef<const char *> Args);
static sourcekitd_response_t
editorFindModuleGroups(StringRef ModuleName, ArrayRef<const char *> Args);
static bool
buildRenameLocationsFromDict(const RequestDict &Req, bool UseNewName,
std::vector<RenameLocations> &RenameLocations,
llvm::SmallString<64> &Error);
static sourcekitd_response_t
createCategorizedEditsResponse(
const RequestResult<ArrayRef<CategorizedEdits>> &Result);
static sourcekitd_response_t
syntacticRename(llvm::MemoryBuffer *InputBuf,
ArrayRef<RenameLocations> RenameLocations,
ArrayRef<const char*> Args);
static sourcekitd_response_t
createCategorizedRenameRangesResponse(
const RequestResult<ArrayRef<CategorizedRenameRanges>> &Result);
static sourcekitd_response_t
findRenameRanges(llvm::MemoryBuffer *InputBuf,
ArrayRef<RenameLocations> RenameLocations,
ArrayRef<const char *> Args);
static bool isSemanticEditorDisabled();
static void enableCompileNotifications(bool value);
namespace {
class SKOptionsDictionary : public OptionsDictionary {
RequestDict Options;
public:
explicit SKOptionsDictionary(RequestDict Options) : Options(Options) {}
bool valueForOption(UIdent Key, unsigned &Val) override {
int64_t result;
if (Options.getInt64(Key, result, false))
return false;
Val = static_cast<unsigned>(result);
return true;
}
bool valueForOption(UIdent Key, bool &Val) override {
int64_t result;
if (Options.getInt64(Key, result, false))
return false;
Val = result ? true : false;
return true;
}
bool valueForOption(UIdent Key, StringRef &Val) override {
Optional<StringRef> value = Options.getString(Key);
if (!value)
return false;
Val = *value;
return true;
}
bool forEach(UIdent key, llvm::function_ref<bool(OptionsDictionary &)> applier) override {
return Options.dictionaryArrayApply(key, [=](RequestDict dict) {
SKOptionsDictionary skDict(dict);
return applier(skDict);
});
}
};
} // anonymous namespace
static void handleRequestImpl(sourcekitd_object_t Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Receiver);
void sourcekitd::handleRequest(sourcekitd_object_t Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Receiver) {
LOG_SECTION("handleRequest-before", InfoHighPrio) {
sourcekitd::printRequestObject(Req, Log->getOS());
}
handleRequestImpl(
Req, CancellationToken,
[Receiver, CancellationToken](sourcekitd_response_t Resp) {
LOG_SECTION("handleRequest-after", InfoHighPrio) {
// Responses are big, print them out with info medium priority.
if (Logger::isLoggingEnabledForLevel(Logger::Level::InfoMediumPrio))
sourcekitd::printResponse(Resp, Log->getOS());
}
sourcekitd::disposeCancellationToken(CancellationToken);
Receiver(Resp);
});
}
void sourcekitd::cancelRequest(SourceKitCancellationToken CancellationToken) {
getGlobalContext().getRequestTracker()->cancel(CancellationToken);
}
void sourcekitd::disposeCancellationToken(
SourceKitCancellationToken CancellationToken) {
getGlobalContext().getRequestTracker()->stopTracking(CancellationToken);
}
bool sourcekitd::requestIsBarrier(sourcekitd_object_t ReqObj) {
RequestDict Req(ReqObj);
sourcekitd_uid_t ReqUID = Req.getUID(KeyRequest);
return ReqUID == RequestEditorOpen || ReqUID == RequestEditorReplaceText ||
ReqUID == RequestEditorClose;
}
bool sourcekitd::requestIsEnableBarriers(sourcekitd_object_t ReqObj) {
RequestDict Req(ReqObj);
sourcekitd_uid_t ReqUID = Req.getUID(KeyRequest);
return ReqUID == RequestEnableRequestBarriers;
}
void sourcekitd::sendBarriersEnabledResponse(ResponseReceiver Receiver) {
ResponseBuilder RespBuilder;
auto Elem = RespBuilder.getDictionary();
Elem.setBool(KeyBarriersEnabled, true);
Receiver(RespBuilder.createResponse());
}
static std::unique_ptr<llvm::MemoryBuffer> getInputBufForRequest(
Optional<StringRef> SourceFile, Optional<StringRef> SourceText,
const Optional<VFSOptions> &vfsOptions, llvm::SmallString<64> &ErrBuf) {
std::unique_ptr<llvm::MemoryBuffer> InputBuf;
if (SourceText.has_value()) {
StringRef BufName;
if (SourceFile.has_value())
BufName = *SourceFile;
else
BufName = "<input>";
InputBuf = llvm::MemoryBuffer::getMemBuffer(*SourceText, BufName);
} else if (vfsOptions.has_value() && SourceFile.has_value()) {
ErrBuf = "using 'key.sourcefile' to read source text from the filesystem "
"is not supported when using 'key.vfs.name'";
return nullptr;
} else if (SourceFile.has_value()) {
llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> FileBufOrErr =
llvm::MemoryBuffer::getFile(*SourceFile);
if (FileBufOrErr) {
InputBuf = std::move(FileBufOrErr.get());
} else {
llvm::raw_svector_ostream OSErr(ErrBuf);
OSErr << "error opening input file '" << *SourceFile << "' ("
<< FileBufOrErr.getError().message() << ')';
return nullptr;
}
} else {
InputBuf = llvm::WritableMemoryBuffer::getNewMemBuffer(0, "<input>");
}
return InputBuf;
}
/// Get the input buffer from 'key.sourcefile' or 'key.sourcetext' value in
/// \p Req . If buffer cannot be retrieved for some reason, Reply an error to
/// \c Rec and returns \c nullptr .
static std::unique_ptr<llvm::MemoryBuffer>
getInputBufForRequestOrEmitError(const RequestDict &Req,
const Optional<VFSOptions> &vfsOptions,
ResponseReceiver Rec) {
Optional<StringRef> SourceFile = Req.getString(KeySourceFile);
Optional<StringRef> SourceText = Req.getString(KeySourceText);
SmallString<64> ErrBuf;
auto buf = getInputBufForRequest(SourceFile, SourceText, vfsOptions, ErrBuf);
if (!buf) {
Rec(createErrorRequestFailed(ErrBuf));
}
return buf;
}
/// Retrieves `key.primary_file` value as a string, or `key.sourcefile` if
/// missing. If both are missing, reply with an error and return \c None.
///
/// The "primary file" is the file to mark as `-primary-file` when building
/// the corresponding AST for this request. The "input file" is the file to
/// resolve any offset or line/column in. These were (prior to
/// \c GeneratedSourceInfo) always the same, but the input file is now able to
/// be a generated buffer name (where that buffer is created during the AST
/// build).
static Optional<StringRef>
getPrimaryFilePathForRequestOrEmitError(const RequestDict &Req,
ResponseReceiver Rec) {
Optional<StringRef> PrimaryFilePath = Req.getString(KeyPrimaryFile);
if (!PrimaryFilePath) {
// Fallback to the old key.sourcefile
PrimaryFilePath = Req.getString(KeySourceFile);
if (!PrimaryFilePath) {
Rec(createErrorRequestInvalid(
"missing 'key.primary_file' and 'key.sourcefile'"));
}
}
return PrimaryFilePath;
}
/// Retrieves `key.sourcefile` only if it is different to `key.primary_file`.
/// Returns an empty string if it's the same or if it was missing. Callers are
/// expected to pull the primary file from the AST if the input file is
/// empty.
///
/// See \c getPrimaryFilePathForRequestOrEmitError for an explanation of primary
/// vs input file.
static StringRef getInputBufferNameForRequest(const RequestDict &Req,
ResponseReceiver Rec) {
Optional<StringRef> PrimaryFilePath = Req.getString(KeyPrimaryFile);
Optional<StringRef> InputBufferName = Req.getString(KeySourceFile);
if (!PrimaryFilePath || PrimaryFilePath == InputBufferName)
return "";
return InputBufferName.value_or("");
}
/// Get compiler arguments from 'key.compilerargs' in \p Req . If the key is
/// missing, reply an error to \c Rec and returns \c true .
static bool
getCompilerArgumentsForRequestOrEmitError(const RequestDict &Req,
SmallVectorImpl<const char *> &Args,
ResponseReceiver Rec) {
bool Failed = Req.getStringArray(KeyCompilerArgs, Args, /*isOptional=*/true);
if (Failed) {
Rec(createErrorRequestInvalid(
"'key.compilerargs' not an array of strings"));
return true;
}
return false;
}
/// Read optional VFSOptions from a request dictionary. The request dictionary
/// *must* outlive the resulting VFSOptions.
/// \returns true on failure and sets \p error.
static Optional<VFSOptions> getVFSOptions(const RequestDict &Req) {
auto name = Req.getString(KeyVFSName);
if (!name)
return None;
std::unique_ptr<OptionsDictionary> options;
if (auto dict = Req.getDictionary(KeyVFSOptions)) {
options = std::make_unique<SKOptionsDictionary>(*dict);
}
return VFSOptions{name->str(), std::move(options)};
}
static bool checkVFSNotSupported(const RequestDict &Req, ResponseReceiver Rec) {
if (Req.getString(KeyVFSName)) {
Rec(createErrorRequestInvalid("This request does not support custom filesystems"));
return true;
}
return false;
}
static void handleSemanticRequest(const RequestDict &Req, ResponseReceiver Rec,
std::function<void()> Fn) {
if (isSemanticEditorDisabled())
return Rec(createErrorRequestFailed("semantic editor is disabled"));
// Typechecking arrays can blow up the stack currently.
// Run them under a malloc'ed stack.
static WorkQueue SemaQueue{WorkQueue::Dequeuing::Concurrent,
"sourcekit.request.semantic"};
++numSemaRequests;
SemaQueue.dispatch([Fn] { Fn(); }, /*isStackDeep=*/true);
}
static void
handleRequestGlobalConfiguration(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
auto Config = getGlobalContext().getGlobalConfiguration();
ResponseBuilder RB;
auto dict = RB.getDictionary();
Optional<unsigned> CompletionMaxASTContextReuseCount =
Req.getOptionalInt64(KeyCompletionMaxASTContextReuseCount)
.transform([](int64_t v) -> unsigned { return v; });
Optional<unsigned> CompletionCheckDependencyInterval =
Req.getOptionalInt64(KeyCompletionCheckDependencyInterval)
.transform([](int64_t v) -> unsigned { return v; });
GlobalConfig::Settings UpdatedConfig =
Config->update(CompletionMaxASTContextReuseCount,
CompletionCheckDependencyInterval);
getGlobalContext().getSwiftLangSupport().globalConfigurationUpdated(Config);
dict.set(KeyCompletionMaxASTContextReuseCount,
UpdatedConfig.IDEInspectionOpts.MaxASTContextReuseCount);
dict.set(KeyCompletionCheckDependencyInterval,
UpdatedConfig.IDEInspectionOpts.CheckDependencyInterval);
return Rec(RB.createResponse());
}
}
static void
handleRequestProtocolVersion(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
ResponseBuilder RB;
auto dict = RB.getDictionary();
dict.set(KeyVersionMajor, ProtocolMajorVersion);
dict.set(KeyVersionMinor, static_cast<int64_t>(ProtocolMinorVersion));
return Rec(RB.createResponse());
}
}
static void
handleRequestCompilerVersion(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
ResponseBuilder RB;
auto dict = RB.getDictionary();
auto thisVersion = swift::version::Version::getCurrentLanguageVersion();
dict.set(KeyVersionMajor, static_cast<int64_t>(thisVersion[0]));
dict.set(KeyVersionMinor, static_cast<int64_t>(thisVersion[1]));
if (thisVersion.size() > 2)
dict.set(KeyVersionPatch, static_cast<int64_t>(thisVersion[2]));
else
dict.set(KeyVersionPatch, static_cast<int64_t>(0));
return Rec(RB.createResponse());
}
}
static void
handleRequestCrashWithExit(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
// 'exit' has the same effect as crashing but without the crash log.
::exit(1);
}
}
static void
handleRequestTestNotification(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
getGlobalContext().getNotificationCenter()->postTestNotification();
return Rec(ResponseBuilder().createResponse());
}
}
static void handleRequestDemangle(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
SmallVector<const char *, 8> MangledNames;
bool Failed = Req.getStringArray(KeyNames, MangledNames, /*isOptional=*/true);
if (Failed) {
return Rec(createErrorRequestInvalid(
"'key.names' not an array of strings"));
}
int64_t Simplified = false;
Req.getInt64(KeySimplified, Simplified, /*isOptional=*/true);
LangSupport &Lang = getGlobalContext().getSwiftLangSupport();
Lang.demangleNames(MangledNames, Simplified, [Rec](auto result) {
if (result.isError())
return Rec(createErrorRequestFailed(result.getError()));
if (result.isCancelled())
return Rec(createErrorRequestFailed(result.getError()));
ResponseBuilder RespBuilder;
auto Arr = RespBuilder.getDictionary().setArray(KeyResults);
for (auto demangldedName : result.value()) {
auto Entry = Arr.appendDictionary();
Entry.set(KeyName, demangldedName.c_str());
}
Rec(RespBuilder.createResponse());
});
}
}
static void
handleRequestMangleSimpleClass(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
SmallVector<std::pair<StringRef, StringRef>, 16> ModuleClassPairs;
sourcekitd_response_t err = nullptr;
bool failed = Req.dictionaryArrayApply(KeyNames, [&](RequestDict dict) {
Optional<StringRef> ModuleName = dict.getString(KeyModuleName);
if (!ModuleName.has_value()) {
err = createErrorRequestInvalid("missing 'key.modulename'");
return true;
}
Optional<StringRef> ClassName = dict.getString(KeyName);
if (!ClassName.has_value()) {
err = createErrorRequestInvalid("missing 'key.name'");
return true;
}
ModuleClassPairs.push_back(std::make_pair(*ModuleName, *ClassName));
return false;
});
if (failed) {
if (!err)
err = createErrorRequestInvalid("missing 'key.names'");
return Rec(err);
}
LangSupport &Lang = getGlobalContext().getSwiftLangSupport();
Lang.mangleSimpleClassNames(ModuleClassPairs, [Rec](auto result) {
if (result.isError())
return Rec(createErrorRequestFailed(result.getError()));
if (result.isCancelled())
return Rec(createErrorRequestFailed(result.getError()));
ResponseBuilder RespBuilder;
auto Arr = RespBuilder.getDictionary().setArray(KeyResults);
for (auto &mangledName : result.value()) {
auto Entry = Arr.appendDictionary();
Entry.set(KeyName, mangledName.c_str());
}
Rec(RespBuilder.createResponse());
});
}
}
static void handleRequestEnableCompileNotifications(
const RequestDict &Req, SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
int64_t value = true;
if (Req.getInt64(KeyValue, value, /*isOptional=*/false)) {
return Rec(createErrorRequestInvalid("missing 'key.value'"));
}
enableCompileNotifications(value);
return Rec(ResponseBuilder().createResponse());
}
}
static void
handleRequestBuildSettingsRegister(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
// Just accept 'source.request.buildsettings.register' for now, don't do
// anything else.
// FIXME: Heavy WIP here.
{ return Rec(ResponseBuilder().createResponse()); }
}
static void
handleRequestDependencyUpdated(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
getGlobalContext().getSwiftLangSupport().dependencyUpdated();
return Rec(ResponseBuilder().createResponse());
}
}
static void handleRequestDocInfo(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<VFSOptions> vfsOptions = getVFSOptions(Req);
SmallVector<const char *, 8> Args;
if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec))
return;
std::unique_ptr<llvm::MemoryBuffer> InputBuf =
getInputBufForRequestOrEmitError(Req, vfsOptions, Rec);
if (!InputBuf)
return;
StringRef ModuleName;
Optional<StringRef> ModuleNameOpt = Req.getString(KeyModuleName);
if (ModuleNameOpt.has_value()) ModuleName = *ModuleNameOpt;
return Rec(reportDocInfo(InputBuf.get(), ModuleName, Args));
}
}
static void
handleRequestEditorOpen(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<VFSOptions> vfsOptions = getVFSOptions(Req);
SmallVector<const char *, 8> Args;
if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec))
return;
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
std::unique_ptr<llvm::MemoryBuffer> InputBuf =
getInputBufForRequestOrEmitError(Req, vfsOptions, Rec);
if (!InputBuf)
return;
int64_t EnableSyntaxMap = true;
Req.getInt64(KeyEnableSyntaxMap, EnableSyntaxMap, /*isOptional=*/true);
int64_t EnableStructure = true;
Req.getInt64(KeyEnableStructure, EnableStructure, /*isOptional=*/true);
int64_t EnableDiagnostics = true;
Req.getInt64(KeyEnableDiagnostics, EnableDiagnostics, /*isOptional=*/true);
int64_t SyntacticOnly = false;
Req.getInt64(KeySyntacticOnly, SyntacticOnly, /*isOptional=*/true);
SKEditorConsumerOptions Opts;
Opts.EnableSyntaxMap = EnableSyntaxMap;
Opts.EnableStructure = EnableStructure;
Opts.EnableDiagnostics = EnableDiagnostics;
Opts.SyntacticOnly = SyntacticOnly;
return Rec(editorOpen(*Name, InputBuf.get(), Opts, Args, std::move(vfsOptions)));
}
}
static void
handleRequestEditorClose(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
// Whether we remove the cached AST from libcache, by default, false.
int64_t RemoveCache = false;
Req.getInt64(KeyRemoveCache, RemoveCache, /*isOptional=*/true);
return Rec(editorClose(*Name, RemoveCache));
}
}
static void
handleRequestEditorReplaceText(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<VFSOptions> vfsOptions = getVFSOptions(Req);
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
std::unique_ptr<llvm::MemoryBuffer> InputBuf =
getInputBufForRequestOrEmitError(Req, vfsOptions, Rec);
if (!InputBuf)
return;
int64_t Offset = 0;
Req.getInt64(KeyOffset, Offset, /*isOptional=*/true);
int64_t Length = 0;
Req.getInt64(KeyLength, Length, /*isOptional=*/true);
int64_t EnableSyntaxMap = true;
Req.getInt64(KeyEnableSyntaxMap, EnableSyntaxMap, /*isOptional=*/true);
int64_t EnableStructure = true;
Req.getInt64(KeyEnableStructure, EnableStructure, /*isOptional=*/true);
int64_t EnableDiagnostics = true;
Req.getInt64(KeyEnableDiagnostics, EnableDiagnostics, /*isOptional=*/true);
int64_t SyntacticOnly = false;
Req.getInt64(KeySyntacticOnly, SyntacticOnly, /*isOptional=*/true);
SKEditorConsumerOptions Opts;
Opts.EnableSyntaxMap = EnableSyntaxMap;
Opts.EnableStructure = EnableStructure;
Opts.EnableDiagnostics = EnableDiagnostics;
Opts.SyntacticOnly = SyntacticOnly;
return Rec(editorReplaceText(*Name, InputBuf.get(), Offset, Length, Opts));
}
}
static void
handleRequestEditorFormatText(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
Optional<RequestDict> FmtOptions = Req.getDictionary(KeyFormatOptions);
if (FmtOptions.has_value())
editorApplyFormatOptions(*Name, *FmtOptions);
int64_t Line = 0;
Req.getInt64(KeyLine, Line, /*isOptional=*/false);
int64_t Length = 0;
Req.getInt64(KeyLength, Length, /*isOptional=*/true);
return Rec(editorFormatText(*Name, Line, Length));
}
}
static void handleRequestEditorExpandPlaceholder(
const RequestDict &Req, SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
int64_t Offset = 0;
Req.getInt64(KeyOffset, Offset, /*isOptional=*/false);
int64_t Length = 0;
Req.getInt64(KeyLength, Length, /*isOptional=*/false);
return Rec(editorExpandPlaceholder(*Name, Offset, Length));
}
}
static void
handleRequestEditorOpenInterface(const RequestDict &Req,
SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
SmallVector<const char *, 8> Args;
if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec))
return;
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
Optional<StringRef> ModuleName = Req.getString(KeyModuleName);
if (!ModuleName.has_value())
return Rec(createErrorRequestInvalid("missing 'key.modulename'"));
Optional<StringRef> GroupName = Req.getString(KeyGroupName);
int64_t SynthesizedExtension = false;
Req.getInt64(KeySynthesizedExtension, SynthesizedExtension,
/*isOptional=*/true);
Optional<StringRef> InterestedUSR = Req.getString(KeyInterestedUSR);
return Rec(editorOpenInterface(*Name, *ModuleName, GroupName, Args,
SynthesizedExtension, InterestedUSR));
}
}
static void handleRequestEditorOpenHeaderInterface(
const RequestDict &Req, SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
SmallVector<const char *, 8> Args;
if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec))
return;
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
Optional<StringRef> HeaderName = Req.getString(KeyFilePath);
if (!HeaderName.has_value())
return Rec(createErrorRequestInvalid("missing 'key.filepath'"));
int64_t SynthesizedExtension = false;
Req.getInt64(KeySynthesizedExtension, SynthesizedExtension,
/*isOptional=*/true);
Optional<int64_t> UsingSwiftArgs = Req.getOptionalInt64(KeyUsingSwiftArgs);
std::string swiftVer;
Optional<StringRef> swiftVerValStr = Req.getString(KeySwiftVersion);
if (swiftVerValStr.has_value()) {
swiftVer = swiftVerValStr.value().str();
} else {
Optional<int64_t> swiftVerVal = Req.getOptionalInt64(KeySwiftVersion);
if (swiftVerVal.has_value())
swiftVer = std::to_string(*swiftVerVal);
}
return Rec(editorOpenHeaderInterface(*Name, *HeaderName, Args,
UsingSwiftArgs.value_or(false),
SynthesizedExtension, swiftVer));
}
}
static void handleRequestEditorOpenSwiftSourceInterface(
const RequestDict &Req, SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
SmallVector<const char *, 8> Args;
if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec))
return;
Optional<StringRef> Name = Req.getString(KeyName);
if (!Name.has_value())
return Rec(createErrorRequestInvalid("missing 'key.name'"));
Optional<StringRef> FileName = Req.getString(KeySourceFile);
if (!FileName.has_value())
return Rec(createErrorRequestInvalid("missing 'key.sourcefile'"));
return editorOpenSwiftSourceInterface(*Name, *FileName, Args,
CancellationToken, Rec);
}
}
static void handleRequestEditorOpenSwiftTypeInterface(
const RequestDict &Req, SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
SmallVector<const char *, 8> Args;
if (getCompilerArgumentsForRequestOrEmitError(Req, Args, Rec))
return;
Optional<StringRef> Usr = Req.getString(KeyUSR);
if (!Usr.has_value())
return Rec(createErrorRequestInvalid("missing 'key.usr'"));
return editorOpenSwiftTypeInterface(*Usr, Args, Rec);
}
}
static void handleRequestEditorExtractTextFromComment(
const RequestDict &Req, SourceKitCancellationToken CancellationToken,
ResponseReceiver Rec) {
{
Optional<StringRef> Source = Req.getString(KeySourceText);
if (!Source.has_value())
return Rec(createErrorRequestInvalid("missing 'key.sourcetext'"));
return Rec(editorExtractTextFromComment(Source.value()));
}
}