-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
SwiftSourceDocInfo.cpp
2244 lines (1995 loc) · 82.3 KB
/
SwiftSourceDocInfo.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
//===--- SwiftSourceDocInfo.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 "SwiftASTManager.h"
#include "SwiftLangSupport.h"
#include "SourceKit/Support/FileSystemProvider.h"
#include "SourceKit/Support/ImmutableTextBuffer.h"
#include "SourceKit/Support/Logging.h"
#include "SourceKit/Support/UIdent.h"
#include "swift/AST/ASTDemangler.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/Decl.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/SwiftNameTranslation.h"
#include "swift/AST/GenericSignature.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/CommentConversion.h"
#include "swift/IDE/ModuleInterfacePrinting.h"
#include "swift/IDE/SourceEntityWalker.h"
#include "swift/IDE/Utils.h"
#include "swift/IDE/Refactoring.h"
#include "swift/IDE/IDERequests.h"
#include "swift/Markup/XMLUtils.h"
#include "swift/Sema/IDETypeChecking.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Module.h"
#include "clang/Index/USRGeneration.h"
#include "clang/Lex/Lexer.h"
#include "llvm/Support/MemoryBuffer.h"
#include <numeric>
using namespace SourceKit;
using namespace swift;
using namespace swift::ide;
namespace {
class AnnotatedDeclarationPrinter : public XMLEscapingPrinter {
public:
AnnotatedDeclarationPrinter(raw_ostream &OS)
:XMLEscapingPrinter(OS) { }
private:
void printTypeRef(Type T, const TypeDecl *TD, Identifier Name) override {
printXML("<Type usr=\"");
SwiftLangSupport::printUSR(TD, OS);
printXML("\">");
StreamPrinter::printTypeRef(T, TD, Name);
printXML("</Type>");
}
};
} // end anonymous namespace
static StringRef getTagForDecl(const Decl *D, bool isRef) {
auto UID = SwiftLangSupport::getUIDForDecl(D, isRef);
static const char *prefix = "source.lang.swift.";
assert(UID.getName().startswith(prefix));
return UID.getName().drop_front(strlen(prefix));
}
static StringRef ExternalParamNameTag = "decl.var.parameter.argument_label";
static StringRef LocalParamNameTag = "decl.var.parameter.name";
static StringRef GenericParamNameTag = "decl.generic_type_param.name";
static StringRef SyntaxKeywordTag = "syntaxtype.keyword";
static StringRef getTagForParameter(PrintStructureKind context) {
switch (context) {
case PrintStructureKind::FunctionParameter:
return "decl.var.parameter";
case PrintStructureKind::FunctionReturnType:
return "decl.function.returntype";
case PrintStructureKind::FunctionType:
return "";
case PrintStructureKind::TupleType:
return "tuple";
case PrintStructureKind::TupleElement:
return "tuple.element";
case PrintStructureKind::GenericParameter:
return "decl.generic_type_param";
case PrintStructureKind::GenericRequirement:
return "decl.generic_type_requirement";
case PrintStructureKind::BuiltinAttribute:
return "syntaxtype.attribute.builtin";
case PrintStructureKind::NumberLiteral:
return "syntaxtype.number";
case PrintStructureKind::StringLiteral:
return "syntaxtype.string";
}
llvm_unreachable("unexpected parameter kind");
}
static StringRef getDeclNameTagForDecl(const Decl *D) {
switch (D->getKind()) {
case DeclKind::Param:
// When we're examining the parameter itself, it is the local name that is
// the name of the variable.
return LocalParamNameTag;
case DeclKind::GenericTypeParam:
return ""; // Handled by printName.
case DeclKind::Constructor:
case DeclKind::Destructor:
case DeclKind::Subscript:
// The names 'init'/'deinit'/'subscript' are actually keywords.
return SyntaxKeywordTag;
default:
return "decl.name";
}
}
namespace {
/// A typesafe union of contexts that the printer can be inside.
/// Currently: Decl, PrintStructureKind
class PrintContext {
// Use the low bit to determine the type; store the enum value shifted left
// to leave the low bit free.
const uintptr_t value;
static constexpr unsigned declTag = 0;
static constexpr unsigned PrintStructureKindTag = 1;
static constexpr unsigned typeTag = 2;
static constexpr unsigned tagMask = 3;
static constexpr unsigned tagShift = 2;
bool hasTag(unsigned tag) const { return (value & tagMask) == tag; }
public:
PrintContext(const Decl *D) : value(uintptr_t(D)) {
static_assert(llvm::PointerLikeTypeTraits<Decl *>::NumLowBitsAvailable >=
tagShift,
"missing spare bit in Decl *");
}
PrintContext(PrintStructureKind K)
: value((uintptr_t(K) << tagShift) | PrintStructureKindTag) {}
PrintContext(TypeLoc unused) : value(typeTag) {}
/// Get the context as a Decl, or nullptr.
const Decl *getDecl() const {
return hasTag(declTag) ? (const Decl *)value : nullptr;
}
/// Get the context as a PrintStructureKind, or None.
Optional<PrintStructureKind> getPrintStructureKind() const {
if (!hasTag(PrintStructureKindTag))
return None;
return PrintStructureKind(value >> tagShift);
}
/// Whether this is a PrintStructureKind context of the given \p kind.
bool is(PrintStructureKind kind) const {
auto storedKind = getPrintStructureKind();
return storedKind && *storedKind == kind;
}
bool isType() const { return hasTag(typeTag); }
};
/// An ASTPrinter for annotating declarations with XML tags that describe the
/// key substructure of the declaration for CursorInfo/DocInfo.
///
/// Prints declarations with decl- and type-specific tags derived from the
/// UIDs used for decl/refs. For example (including newlines purely for ease of
/// reading):
///
/// \verbatim
/// <decl.function.free>
/// func <decl.name>foo</decl.name>
/// (
/// <decl.var.parameter>
/// <decl.var.parameter.name>x</decl.var.parameter.name>:
/// <ref.struct usr="Si">Int</ref.struct>
/// </decl.var.parameter>
/// ) -> <decl.function.returntype>
/// <ref.struct usr="Si">Int</ref.struct></decl.function.returntype>
/// </decl.function.free>
/// \endverbatim
class FullyAnnotatedDeclarationPrinter final : public XMLEscapingPrinter {
public:
FullyAnnotatedDeclarationPrinter(raw_ostream &OS) : XMLEscapingPrinter(OS) {}
private:
// MARK: The ASTPrinter callback interface.
void printDeclPre(const Decl *D, Optional<BracketOptions> Bracket) override {
contextStack.emplace_back(PrintContext(D));
openTag(getTagForDecl(D, /*isRef=*/false));
}
void printDeclPost(const Decl *D, Optional<BracketOptions> Bracket) override {
assert(contextStack.back().getDecl() == D && "unmatched printDeclPre");
contextStack.pop_back();
closeTag(getTagForDecl(D, /*isRef=*/false));
}
void printDeclLoc(const Decl *D) override {
auto tag = getDeclNameTagForDecl(D);
if (!tag.empty())
openTag(tag);
}
void printDeclNameEndLoc(const Decl *D) override {
auto tag = getDeclNameTagForDecl(D);
if (!tag.empty())
closeTag(tag);
}
void printTypePre(const TypeLoc &TL) override {
auto tag = getTypeTagForCurrentContext();
contextStack.emplace_back(PrintContext(TL));
if (!tag.empty())
openTag(tag);
}
void printTypePost(const TypeLoc &TL) override {
assert(contextStack.back().isType());
contextStack.pop_back();
auto tag = getTypeTagForCurrentContext();
if (!tag.empty())
closeTag(tag);
}
void printStructurePre(PrintStructureKind kind, const Decl *D) override {
if (kind == PrintStructureKind::TupleElement ||
kind == PrintStructureKind::TupleType)
fixupTuple(kind);
contextStack.emplace_back(PrintContext(kind));
auto tag = getTagForParameter(kind);
if (tag.empty())
return;
if (D && kind == PrintStructureKind::GenericParameter) {
assert(isa<ValueDecl>(D) && "unexpected non-value decl for param");
openTagWithUSRForDecl(tag, cast<ValueDecl>(D));
} else {
openTag(tag);
}
}
void printStructurePost(PrintStructureKind kind, const Decl *D) override {
if (kind == PrintStructureKind::TupleElement ||
kind == PrintStructureKind::TupleType) {
auto prev = contextStack.pop_back_val();
(void)prev;
fixupTuple(kind);
assert(prev.is(kind) && "unmatched printStructurePre");
} else {
assert(contextStack.back().is(kind) && "unmatched printStructurePre");
contextStack.pop_back();
}
auto tag = getTagForParameter(kind);
if (!tag.empty())
closeTag(tag);
}
void printNamePre(PrintNameContext context) override {
auto tag = getTagForPrintNameContext(context);
if (!tag.empty())
openTag(tag);
}
void printNamePost(PrintNameContext context) override {
auto tag = getTagForPrintNameContext(context);
if (!tag.empty())
closeTag(tag);
}
void printTypeRef(Type T, const TypeDecl *TD, Identifier name) override {
auto tag = getTagForDecl(TD, /*isRef=*/true);
openTagWithUSRForDecl(tag, TD);
insideRef = true;
XMLEscapingPrinter::printTypeRef(T, TD, name);
insideRef = false;
closeTag(tag);
}
// MARK: Convenience functions for printing.
void openTag(StringRef tag) { OS << "<" << tag << ">"; }
void closeTag(StringRef tag) { OS << "</" << tag << ">"; }
void openTagWithUSRForDecl(StringRef tag, const ValueDecl *VD) {
OS << "<" << tag << " usr=\"";
SwiftLangSupport::printUSR(VD, OS);
OS << "\">";
}
// MARK: Misc.
StringRef getTypeTagForCurrentContext() const {
if (contextStack.empty())
return "";
static StringRef parameterTypeTag = "decl.var.parameter.type";
static StringRef genericParamTypeTag = "decl.generic_type_param.constraint";
auto context = contextStack.back();
if (context.is(PrintStructureKind::FunctionParameter))
return parameterTypeTag;
if (context.is(PrintStructureKind::GenericParameter))
return genericParamTypeTag;
if (context.is(PrintStructureKind::TupleElement))
return "tuple.element.type";
if (context.getPrintStructureKind().hasValue() || context.isType())
return "";
assert(context.getDecl() && "unexpected context kind");
switch (context.getDecl()->getKind()) {
case DeclKind::Param:
return parameterTypeTag;
case DeclKind::GenericTypeParam:
return genericParamTypeTag;
case DeclKind::Var:
return "decl.var.type";
case DeclKind::Subscript:
case DeclKind::Func:
default:
return "";
}
}
StringRef getTagForPrintNameContext(PrintNameContext context) {
if (insideRef)
return "";
bool insideParam =
!contextStack.empty() &&
contextStack.back().is(PrintStructureKind::FunctionParameter);
switch (context) {
case PrintNameContext::FunctionParameterExternal:
return ExternalParamNameTag;
case PrintNameContext::FunctionParameterLocal:
return LocalParamNameTag;
case PrintNameContext::TupleElement:
if (insideParam)
return ExternalParamNameTag;
return "tuple.element.argument_label";
case PrintNameContext::Keyword:
return SyntaxKeywordTag;
case PrintNameContext::GenericParameter:
return GenericParamNameTag;
case PrintNameContext::Attribute:
return "syntaxtype.attribute.name";
default:
return "";
}
}
/// 'Fix' a tuple or tuple element structure kind to be a function parameter
/// or function type if we are currently inside a function type. This
/// simplifies functions that need to differentiate a tuple from the input
/// part of a function type.
void fixupTuple(PrintStructureKind &kind) {
assert(kind == PrintStructureKind::TupleElement ||
kind == PrintStructureKind::TupleType);
// Skip over 'type's in the context stack.
for (auto I = contextStack.rbegin(), E = contextStack.rend(); I != E; ++I) {
if (I->is(PrintStructureKind::FunctionType)) {
if (kind == PrintStructureKind::TupleElement)
kind = PrintStructureKind::FunctionParameter;
else
kind = PrintStructureKind::FunctionType;
break;
} else if (!I->isType()) {
break;
}
}
}
private:
/// A stack of contexts being printed, used to determine the context for
/// subsequent ASTPrinter callbacks.
llvm::SmallVector<PrintContext, 3> contextStack;
bool insideRef = false;
};
} // end anonymous namespace
static Type findBaseTypeForReplacingArchetype(const ValueDecl *VD, const Type Ty) {
if (Ty.isNull())
return Type();
// Find the nominal type decl related to VD.
if (!VD->getDeclContext()->isTypeContext())
return Type();
return Ty->getRValueType()->getInOutObjectType()->getMetatypeInstanceType();
}
static void printAnnotatedDeclaration(const ValueDecl *VD,
const Type BaseTy,
raw_ostream &OS) {
AnnotatedDeclarationPrinter Printer(OS);
PrintOptions PO = PrintOptions::printQuickHelpDeclaration();
if (BaseTy) {
PO.setBaseType(BaseTy);
PO.PrintAsMember = true;
}
// If it's implicit, try to find an overridden ValueDecl that's not implicit.
// This will ensure we can properly annotate TypeRepr with a usr
// in AnnotatedDeclarationPrinter.
while (VD->isImplicit() && VD->getOverriddenDecl())
VD = VD->getOverriddenDecl();
// If this is a property wrapper backing property (_foo) or projected value
// ($foo) and the wrapped property is not implicit, still print it.
if (auto *VarD = dyn_cast<VarDecl>(VD)) {
if (auto *Wrapped = VarD->getOriginalWrappedProperty()) {
if (!Wrapped->isImplicit())
PO.TreatAsExplicitDeclList.push_back(VD);
}
}
// Wrap this up in XML, as that's what we'll use for documentation comments.
OS<<"<Declaration>";
VD->print(Printer, PO);
OS<<"</Declaration>";
}
void SwiftLangSupport::printFullyAnnotatedDeclaration(const ValueDecl *VD,
Type BaseTy,
raw_ostream &OS) {
FullyAnnotatedDeclarationPrinter Printer(OS);
PrintOptions PO = PrintOptions::printQuickHelpDeclaration();
if (BaseTy) {
PO.setBaseType(BaseTy);
PO.PrintAsMember = true;
}
// If it's implicit, try to find an overridden ValueDecl that's not implicit.
// This will ensure we can properly annotate TypeRepr with a usr
// in AnnotatedDeclarationPrinter.
while (VD->isImplicit() && VD->getOverriddenDecl())
VD = VD->getOverriddenDecl();
// If this is a property wrapper backing property (_foo) or projected value
// ($foo) and the wrapped property is not implicit, still print it.
if (auto *VarD = dyn_cast<VarDecl>(VD)) {
if (auto *Wrapped = VarD->getOriginalWrappedProperty()) {
if (!Wrapped->isImplicit())
PO.TreatAsExplicitDeclList.push_back(VD);
}
}
VD->print(Printer, PO);
}
void SwiftLangSupport::printFullyAnnotatedGenericReq(
const swift::GenericSignature *Sig, llvm::raw_ostream &OS) {
assert(Sig);
FullyAnnotatedDeclarationPrinter Printer(OS);
PrintOptions PO = PrintOptions::printQuickHelpDeclaration();
Sig->print(Printer, PO);
}
void SwiftLangSupport::printFullyAnnotatedSynthesizedDeclaration(
const swift::ValueDecl *VD, TypeOrExtensionDecl Target,
llvm::raw_ostream &OS) {
// FIXME: Mutable global variable - gross!
static llvm::SmallDenseMap<swift::ValueDecl*,
std::unique_ptr<swift::SynthesizedExtensionAnalyzer>> TargetToAnalyzerMap;
FullyAnnotatedDeclarationPrinter Printer(OS);
PrintOptions PO = PrintOptions::printQuickHelpDeclaration();
NominalTypeDecl *TargetNTD = Target.getBaseNominal();
if (TargetToAnalyzerMap.count(TargetNTD) == 0) {
std::unique_ptr<SynthesizedExtensionAnalyzer> Analyzer(
new SynthesizedExtensionAnalyzer(TargetNTD, PO));
TargetToAnalyzerMap.insert({TargetNTD, std::move(Analyzer)});
}
PO.initForSynthesizedExtension(Target);
PO.PrintAsMember = true;
VD->print(Printer, PO);
}
template <typename FnTy>
void walkRelatedDecls(const ValueDecl *VD, const FnTy &Fn) {
llvm::SmallDenseMap<DeclName, unsigned, 16> NamesSeen;
++NamesSeen[VD->getFullName()];
SmallVector<LookupResultEntry, 8> RelatedDecls;
if (isa<ParamDecl>(VD))
return; // Parameters don't have interesting related declarations.
// FIXME: Extract useful related declarations, overloaded functions,
// if VD is an initializer, we should extract other initializers etc.
// For now we use UnqualifiedLookup to fetch other declarations with the same
// base name.
auto TypeResolver = VD->getASTContext().getLazyResolver();
UnqualifiedLookup Lookup(VD->getBaseName(), VD->getDeclContext(),
TypeResolver);
for (auto result : Lookup.Results) {
ValueDecl *RelatedVD = result.getValueDecl();
if (RelatedVD->getAttrs().isUnavailable(VD->getASTContext()))
continue;
if (RelatedVD != VD) {
++NamesSeen[RelatedVD->getFullName()];
RelatedDecls.push_back(result);
}
}
// Now provide the results along with whether the name is duplicate or not.
ValueDecl *OriginalBase = VD->getDeclContext()->getSelfNominalTypeDecl();
for (auto Related : RelatedDecls) {
ValueDecl *RelatedVD = Related.getValueDecl();
bool SameBase = Related.getBaseDecl() && Related.getBaseDecl() == OriginalBase;
Fn(RelatedVD, SameBase, NamesSeen[RelatedVD->getFullName()] > 1);
}
}
//===----------------------------------------------------------------------===//
// SwiftLangSupport::getCursorInfo
//===----------------------------------------------------------------------===//
static StringRef getSourceToken(unsigned Offset,
ImmutableTextSnapshotRef Snap) {
auto MemBuf = Snap->getBuffer()->getInternalBuffer();
// FIXME: Invalid offset shouldn't reach here.
if (Offset >= MemBuf->getBufferSize())
return StringRef();
SourceManager SM;
auto MemBufRef = llvm::MemoryBuffer::getMemBuffer(MemBuf->getBuffer(),
MemBuf->getBufferIdentifier());
auto BufId = SM.addNewSourceBuffer(std::move(MemBufRef));
SourceLoc Loc = SM.getLocForOffset(BufId, Offset);
return Lexer::getTokenAtLocation(SM, Loc).getText();
}
static llvm::Optional<unsigned>
mapOffsetToOlderSnapshot(unsigned Offset,
ImmutableTextSnapshotRef NewSnap,
ImmutableTextSnapshotRef OldSnap) {
SmallVector<ReplaceImmutableTextUpdateRef, 16> Updates;
OldSnap->foreachReplaceUntil(NewSnap,
[&](ReplaceImmutableTextUpdateRef Upd)->bool {
Updates.push_back(Upd);
return true;
});
// Walk the updates backwards and "undo" them.
for (auto I = Updates.rbegin(), E = Updates.rend(); I != E; ++I) {
auto Upd = *I;
if (Upd->getByteOffset() <= Offset &&
Offset < Upd->getByteOffset() + Upd->getText().size())
return None; // Offset is part of newly inserted text.
if (Upd->getByteOffset() <= Offset) {
Offset += Upd->getLength(); // "bring back" what was removed.
Offset -= Upd->getText().size(); // "remove" what was added.
}
}
return Offset;
}
static llvm::Optional<unsigned>
mapOffsetToNewerSnapshot(unsigned Offset,
ImmutableTextSnapshotRef OldSnap,
ImmutableTextSnapshotRef NewSnap) {
bool Completed = OldSnap->foreachReplaceUntil(NewSnap,
[&](ReplaceImmutableTextUpdateRef Upd)->bool {
if (Upd->getByteOffset() <= Offset &&
Offset < Upd->getByteOffset() + Upd->getLength())
return false; // Offset is part of removed text.
if (Upd->getByteOffset() <= Offset) {
Offset += Upd->getText().size();
Offset -= Upd->getLength();
}
return true;
});
if (Completed)
return Offset;
return None;
}
/// Tries to remap the location from a previous snapshot to the latest one.
static llvm::Optional<std::pair<unsigned, unsigned>>
tryRemappingLocToLatestSnapshot(SwiftLangSupport &Lang,
std::pair<unsigned, unsigned> Range,
StringRef Filename,
ArrayRef<ImmutableTextSnapshotRef> PreviousASTSnaps) {
ImmutableTextSnapshotRef LatestSnap;
if (auto EditorDoc = Lang.getEditorDocuments()->findByPath(Filename))
LatestSnap = EditorDoc->getLatestSnapshot();
if (!LatestSnap)
return Range;
for (auto &PrevSnap : PreviousASTSnaps) {
if (PrevSnap->isFromSameBuffer(LatestSnap)) {
if (PrevSnap->getStamp() == LatestSnap->getStamp())
return Range;
auto OptBegin = mapOffsetToNewerSnapshot(Range.first,
PrevSnap, LatestSnap);
if (!OptBegin.hasValue())
return None;
auto OptEnd = mapOffsetToNewerSnapshot(Range.first+Range.second,
PrevSnap, LatestSnap);
if (!OptEnd.hasValue())
return None;
return std::make_pair(*OptBegin, *OptEnd-*OptBegin);
}
}
return Range;
}
/// Returns true for error.
static bool passCursorInfoForModule(ModuleEntity Mod,
SwiftInterfaceGenMap &IFaceGenContexts,
const CompilerInvocation &Invok,
std::function<void(const RequestResult<CursorInfoData> &)> Receiver) {
std::string Name = Mod.getName();
std::string FullName = Mod.getFullName();
CursorInfoData Info;
Info.Kind = SwiftLangSupport::getUIDForModuleRef();
Info.Name = Name;
Info.ModuleName = FullName;
if (auto IFaceGenRef = IFaceGenContexts.find(Info.ModuleName, Invok))
Info.ModuleInterfaceName = IFaceGenRef->getDocumentName();
Info.IsSystem = Mod.isSystemModule();
std::vector<StringRef> Groups;
if (auto MD = Mod.getAsSwiftModule()) {
Info.ModuleGroupArray = ide::collectModuleGroups(const_cast<ModuleDecl*>(MD),
Groups);
}
Receiver(RequestResult<CursorInfoData>::fromResult(Info));
return false;
}
static void
collectAvailableRenameInfo(const ValueDecl *VD,
std::vector<UIdent> &RefactoringIds,
DelayedStringRetriever &RefactroingNameOS,
DelayedStringRetriever &RefactoringReasonOS) {
std::vector<ide::RenameAvailabiliyInfo> Scratch;
for (auto Info : ide::collectRenameAvailabilityInfo(VD, Scratch)) {
RefactoringIds.push_back(SwiftLangSupport::
getUIDForRefactoringKind(Info.Kind));
RefactroingNameOS.startPiece();
RefactroingNameOS << ide::getDescriptiveRefactoringKindName(Info.Kind);
RefactroingNameOS.endPiece();
RefactoringReasonOS.startPiece();
RefactoringReasonOS << ide::getDescriptiveRenameUnavailableReason(Info.
AvailableKind);
RefactoringReasonOS.endPiece();
}
}
static void
serializeRefactoringKinds(ArrayRef<RefactoringKind> AllKinds,
std::vector<UIdent> &RefactoringIds,
DelayedStringRetriever &RefactroingNameOS,
DelayedStringRetriever &RefactoringReasonOS) {
for (auto Kind : AllKinds) {
RefactoringIds.push_back(SwiftLangSupport::getUIDForRefactoringKind(Kind));
RefactroingNameOS.startPiece();
RefactroingNameOS << ide::getDescriptiveRefactoringKindName(Kind);
RefactroingNameOS.endPiece();
RefactoringReasonOS.startPiece();
RefactoringReasonOS.endPiece();
}
}
static void
collectAvailableRefactoringsOtherThanRename(SourceFile *SF,
ResolvedCursorInfo CursorInfo,
std::vector<UIdent> &RefactoringIds,
DelayedStringRetriever &RefactroingNameOS,
DelayedStringRetriever &RefactoringReasonOS) {
std::vector<RefactoringKind> Scratch;
serializeRefactoringKinds(collectAvailableRefactorings(SF, CursorInfo, Scratch,
/*ExcludeRename*/true), RefactoringIds, RefactroingNameOS,
RefactoringReasonOS);
}
static Optional<unsigned>
getParamParentNameOffset(const ValueDecl *VD, SourceLoc Cursor) {
if (Cursor.isInvalid())
return None;
SourceLoc Loc;
if (auto PD = dyn_cast<ParamDecl>(VD)) {
// Avoid returning parent loc for internal-only names.
if (PD->getArgumentNameLoc().isValid() && PD->getArgumentNameLoc() != Cursor)
return None;
auto *DC = PD->getDeclContext();
switch (DC->getContextKind()) {
case DeclContextKind::SubscriptDecl:
Loc = cast<SubscriptDecl>(DC)->getNameLoc();
break;
case DeclContextKind::AbstractFunctionDecl:
Loc = cast<AbstractFunctionDecl>(DC)->getNameLoc();
break;
default:
break;
}
}
if (Loc.isInvalid())
return None;
auto &SM = VD->getASTContext().SourceMgr;
return SM.getLocOffsetInBuffer(Loc, SM.findBufferContainingLoc(Loc));
}
/// Returns true on success, false on error (and sets `Diagnostic` accordingly).
static bool passCursorInfoForDecl(SourceFile* SF,
const ValueDecl *VD,
const ModuleDecl *MainModule,
const Type ContainerTy,
bool IsRef,
bool RetrieveRefactoring,
ResolvedCursorInfo TheTok,
Optional<unsigned> OrigBufferID,
SourceLoc CursorLoc,
ArrayRef<RefactoringInfo> KownRefactoringInfoFromRange,
SwiftLangSupport &Lang,
const CompilerInvocation &Invok,
std::string &Diagnostic,
ArrayRef<ImmutableTextSnapshotRef> PreviousASTSnaps,
std::function<void(const RequestResult<CursorInfoData> &)> Receiver) {
if (AvailableAttr::isUnavailable(VD)) {
Diagnostic = "Unavailable in the current compilation context.";
return false;
}
SmallString<64> SS;
auto BaseType = findBaseTypeForReplacingArchetype(VD, ContainerTy);
bool InSynthesizedExtension = false;
if (BaseType) {
if (auto Target = BaseType->getAnyNominal()) {
SynthesizedExtensionAnalyzer Analyzer(Target,
PrintOptions::printModuleInterface());
InSynthesizedExtension = Analyzer.isInSynthesizedExtension(VD);
}
}
unsigned NameBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
SwiftLangSupport::printDisplayName(VD, OS);
}
unsigned NameEnd = SS.size();
// If VD is the syntehsized property wrapper backing storage (_foo) or
// projected value ($foo) of a property (foo), use that property's USR instead
// so that a rename refactoring renames all three (foo, $foo, and _foo).
const ValueDecl* OriginalProperty = VD;
if (auto *VarD = dyn_cast<VarDecl>(VD)) {
if (auto *Wrapped = VarD->getOriginalWrappedProperty())
OriginalProperty = Wrapped;
}
unsigned USRBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
SwiftLangSupport::printUSR(OriginalProperty, OS);
if (InSynthesizedExtension) {
OS << LangSupport::SynthesizedUSRSeparator;
SwiftLangSupport::printUSR(BaseType->getAnyNominal(), OS);
}
}
unsigned USREnd = SS.size();
unsigned TypenameBegin = SS.size();
if (VD->hasInterfaceType()) {
llvm::raw_svector_ostream OS(SS);
PrintOptions Options;
Options.PrintTypeAliasUnderlyingType = true;
VD->getInterfaceType().print(OS, Options);
}
unsigned TypenameEnd = SS.size();
unsigned MangledTypeStart = SS.size();
{
llvm::raw_svector_ostream OS(SS);
SwiftLangSupport::printDeclTypeUSR(VD, OS);
}
unsigned MangledTypeEnd = SS.size();
unsigned MangledContainerTypeStart = SS.size();
if (ContainerTy && !ContainerTy->hasArchetype()) {
llvm::raw_svector_ostream OS(SS);
SwiftLangSupport::printTypeUSR(ContainerTy, OS);
}
unsigned MangledContainerTypeEnd = SS.size();
// If VD is the syntehsized property wrapper backing storage (_foo) or
// projected value ($foo) of a property (foo), use that property's
// documentation instead.
unsigned DocCommentBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
ide::getDocumentationCommentAsXML(OriginalProperty, OS);
}
unsigned DocCommentEnd = SS.size();
unsigned DeclBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
printAnnotatedDeclaration(VD, BaseType, OS);
}
unsigned DeclEnd = SS.size();
unsigned FullDeclBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
SwiftLangSupport::printFullyAnnotatedDeclaration(VD, BaseType, OS);
}
unsigned FullDeclEnd = SS.size();
unsigned GroupBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
auto *GroupVD = InSynthesizedExtension ? BaseType->getAnyNominal() : VD;
if (auto OP = GroupVD->getGroupName())
OS << OP.getValue();
}
unsigned GroupEnd = SS.size();
unsigned LocalizationBegin = SS.size();
{
llvm::raw_svector_ostream OS(SS);
ide::getLocalizationKey(VD, OS);
}
unsigned LocalizationEnd = SS.size();
std::vector<UIdent> RefactoringIds;
DelayedStringRetriever RefactoringNameOS(SS);
DelayedStringRetriever RefactoringReasonOS(SS);
if (RetrieveRefactoring) {
collectAvailableRenameInfo(VD, RefactoringIds, RefactoringNameOS,
RefactoringReasonOS);
collectAvailableRefactoringsOtherThanRename(SF, TheTok, RefactoringIds,
RefactoringNameOS, RefactoringReasonOS);
}
DelayedStringRetriever OverUSRsStream(SS);
ide::walkOverriddenDecls(VD,
[&](llvm::PointerUnion<const ValueDecl*, const clang::NamedDecl*> D) {
OverUSRsStream.startPiece();
if (auto VD = D.dyn_cast<const ValueDecl*>()) {
if (SwiftLangSupport::printUSR(VD, OverUSRsStream))
return;
} else {
llvm::SmallString<128> Buf;
if (clang::index::generateUSRForDecl(
D.get<const clang::NamedDecl*>(), Buf))
return;
OverUSRsStream << Buf.str();
}
OverUSRsStream.endPiece();
});
DelayedStringRetriever RelDeclsStream(SS);
walkRelatedDecls(VD, [&](const ValueDecl *RelatedDecl, bool UseOriginalBase, bool DuplicateName) {
RelDeclsStream.startPiece();
{
RelDeclsStream<<"<RelatedName usr=\"";
SwiftLangSupport::printUSR(RelatedDecl, RelDeclsStream);
RelDeclsStream<<"\">";
if (isa<AbstractFunctionDecl>(RelatedDecl) && DuplicateName) {
// Related decls are generally overloads, so print parameter types to
// differentiate them.
PrintOptions PO;
PO.SkipAttributes = true;
PO.SkipIntroducerKeywords = true;
PO.ArgAndParamPrinting = PrintOptions::ArgAndParamPrintingMode::ArgumentOnly;
XMLEscapingPrinter Printer(RelDeclsStream);
if (UseOriginalBase && BaseType) {
PO.setBaseType(BaseType);
PO.PrintAsMember = true;
}
RelatedDecl->print(Printer, PO);
} else {
llvm::SmallString<128> Buf;
{
llvm::raw_svector_ostream OSBuf(Buf);
SwiftLangSupport::printDisplayName(RelatedDecl, OSBuf);
}
swift::markup::appendWithXMLEscaping(RelDeclsStream, Buf);
}
RelDeclsStream<<"</RelatedName>";
}
RelDeclsStream.endPiece();
});
ASTContext &Ctx = VD->getASTContext();
ClangImporter *Importer = static_cast<ClangImporter*>(
Ctx.getClangModuleLoader());
std::string ModuleName;
auto ClangNode = VD->getClangNode();
if (ClangNode) {
auto ClangMod = Importer->getClangOwningModule(ClangNode);
if (ClangMod)
ModuleName = ClangMod->getFullModuleName();
} else if (VD->getLoc().isInvalid() && VD->getModuleContext() != MainModule) {
ModuleName = VD->getModuleContext()->getName().str();
}
StringRef ModuleInterfaceName;
if (auto IFaceGenRef = Lang.getIFaceGenContexts().find(ModuleName, Invok))
ModuleInterfaceName = IFaceGenRef->getDocumentName();
UIdent Kind = SwiftLangSupport::getUIDForDecl(VD, IsRef);
StringRef Name = StringRef(SS.begin()+NameBegin, NameEnd-NameBegin);
StringRef USR = StringRef(SS.begin()+USRBegin, USREnd-USRBegin);
StringRef TypeName = StringRef(SS.begin()+TypenameBegin,
TypenameEnd-TypenameBegin);
StringRef TypeUsr = StringRef(SS.begin()+MangledTypeStart,
MangledTypeEnd - MangledTypeStart);
StringRef ContainerTypeUsr = StringRef(SS.begin()+MangledContainerTypeStart,
MangledContainerTypeEnd - MangledContainerTypeStart);
StringRef DocComment = StringRef(SS.begin()+DocCommentBegin,
DocCommentEnd-DocCommentBegin);
StringRef AnnotatedDecl = StringRef(SS.begin()+DeclBegin,
DeclEnd-DeclBegin);
StringRef FullyAnnotatedDecl =
StringRef(SS.begin() + FullDeclBegin, FullDeclEnd - FullDeclBegin);
StringRef GroupName = StringRef(SS.begin() + GroupBegin, GroupEnd - GroupBegin);
StringRef LocalizationKey = StringRef(SS.begin() + LocalizationBegin,
LocalizationEnd - LocalizationBegin);
// If VD is the syntehsized property wrapper backing storage (_foo) or
// projected value ($foo) of a property (foo), base the location on that
// property instead.
llvm::Optional<std::pair<unsigned, unsigned>> DeclarationLoc;
StringRef Filename;
getLocationInfo(OriginalProperty, DeclarationLoc, Filename);
if (DeclarationLoc.hasValue()) {
DeclarationLoc = tryRemappingLocToLatestSnapshot(Lang,
*DeclarationLoc,
Filename,
PreviousASTSnaps);
if (!DeclarationLoc.hasValue()) {
Diagnostic = "Failed to remap declaration to latest snapshot.";
return false;
}
}
SmallVector<StringRef, 4> OverUSRs;
OverUSRsStream.retrieve([&](StringRef S) { OverUSRs.push_back(S); });
SmallVector<StringRef, 4> AnnotatedRelatedDecls;
RelDeclsStream.retrieve([&](StringRef S) { AnnotatedRelatedDecls.push_back(S); });
SmallVector<RefactoringInfo, 4> RefactoringInfoBuffer;
for (unsigned I = 0, N = RefactoringIds.size(); I < N; I ++) {
RefactoringInfoBuffer.push_back({RefactoringIds[I], RefactoringNameOS[I],
RefactoringReasonOS[I]});
}
// Add available refactoring inheritted from range.
RefactoringInfoBuffer.insert(RefactoringInfoBuffer.end(),
KownRefactoringInfoFromRange.begin(),
KownRefactoringInfoFromRange.end());
bool IsSystem = VD->getModuleContext()->isSystemModule();
std::string TypeInterface;
CursorInfoData Info;
Info.Kind = Kind;
Info.Name = Name;
Info.USR = USR;
Info.TypeName = TypeName;
Info.TypeUSR = TypeUsr;
Info.ContainerTypeUSR = ContainerTypeUsr;
Info.DocComment = DocComment;
Info.AnnotatedDeclaration = AnnotatedDecl;
Info.FullyAnnotatedDeclaration = FullyAnnotatedDecl;
Info.ModuleName = ModuleName;
Info.ModuleInterfaceName = ModuleInterfaceName;
Info.DeclarationLoc = DeclarationLoc;
Info.Filename = Filename;
Info.OverrideUSRs = OverUSRs;
Info.AnnotatedRelatedDeclarations = AnnotatedRelatedDecls;
Info.GroupName = GroupName;
Info.LocalizationKey = LocalizationKey;
Info.IsSystem = IsSystem;
Info.TypeInterface = StringRef();
Info.AvailableActions = llvm::makeArrayRef(RefactoringInfoBuffer);
Info.ParentNameOffset = getParamParentNameOffset(VD, CursorLoc);
Receiver(RequestResult<CursorInfoData>::fromResult(Info));
return true;
}