forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASTPrinter.cpp
4242 lines (3705 loc) · 127 KB
/
ASTPrinter.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
//===--- ASTPrinter.cpp - Swift Language AST Printer ----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements printing for the Swift ASTs.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/AST/TypeWalker.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/Fallthrough.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Config.h"
#include "swift/Parse/Lexer.h"
#include "swift/Sema/IDETypeChecking.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/Module.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <queue>
using namespace swift;
namespace swift {
struct SynthesizedExtensionAnalyzer::Implementation {
static bool isMemberFavored(const NominalTypeDecl* Target, const Decl* D) {
DeclContext* DC = Target->getDeclContext();
Type BaseTy = Target->getDeclaredTypeInContext();
const FuncDecl *FD = dyn_cast<FuncDecl>(D);
if (!FD)
return true;
ResolveMemberResult Result = resolveValueMember(*DC, BaseTy,
FD->getEffectiveFullName());
return !(Result && Result.Favored != D);
}
static bool isExtensionFavored(const NominalTypeDecl* Target,
const ExtensionDecl *ED) {
return std::find_if(ED->getMembers().begin(), ED->getMembers().end(),
[&](DeclIterator It) { return isMemberFavored(Target, *It);}) !=
ED->getMembers().end();
}
struct SynthesizedExtensionInfo {
ExtensionDecl *Ext = nullptr;
bool IsSynthesized;
operator bool() const { return Ext; }
SynthesizedExtensionInfo(bool IsSynthesized = true) :
IsSynthesized(IsSynthesized) {}
bool operator< (const SynthesizedExtensionInfo& Rhs) const {
// Synthesized are always after actual ones.
if (IsSynthesized != Rhs.IsSynthesized)
return !IsSynthesized;
// If not from the same file, sort by file name.
if (auto LFile = Ext->getSourceFileName()) {
if (auto RFile = Rhs.Ext->getSourceFileName()) {
int Result = LFile.getValue().compare(RFile.getValue());
if (Result != 0)
return Result < 0;
}
}
// Otherwise, sort by source order.
if (auto LeftOrder = Ext->getSourceOrder()) {
if (auto RightOrder = Rhs.Ext->getSourceOrder()) {
return LeftOrder.getValue() < RightOrder.getValue();
}
}
return false;
}
};
struct ExtensionMergeInfo {
struct Requirement {
Type First;
Type Second;
RequirementKind Kind;
bool operator< (const Requirement& Rhs) const {
if (Kind != Rhs.Kind)
return Kind < Rhs.Kind;
else if (First.getPointer() != Rhs.First.getPointer())
return First.getPointer() < Rhs.First.getPointer();
else
return Second.getPointer() < Rhs.Second.getPointer();
}
bool operator== (const Requirement& Rhs) const {
return (!(*this < Rhs)) && (!(Rhs < *this));
}
};
bool HasDocComment;
unsigned InheritsCount;
std::set<Requirement> Requirements;
void addRequirement(Type First, Type Second, RequirementKind Kind) {
Requirements.insert({First, Second, Kind});
}
bool operator== (const ExtensionMergeInfo& Another) const {
// Trivially unmergeable.
if (HasDocComment || Another.HasDocComment)
return false;
if (InheritsCount != 0 || Another.InheritsCount != 0)
return false;
return Requirements == Another.Requirements;
}
bool isMergeableWithTypeDef() {
return !HasDocComment && InheritsCount == 0 && Requirements.empty();
}
};
typedef llvm::MapVector<ExtensionDecl*, SynthesizedExtensionInfo> ExtensionInfoMap;
typedef llvm::MapVector<ExtensionDecl*, ExtensionMergeInfo> ExtensionMergeInfoMap;
struct ExtensionMergeGroup {
unsigned RequirementsCount;
unsigned InheritanceCount;
MergeGroupKind Kind;
std::vector<SynthesizedExtensionInfo*> Members;
ExtensionMergeGroup(SynthesizedExtensionInfo *Info,
unsigned RequirementsCount,
unsigned InheritanceCount,
bool MergeableWithType) :
RequirementsCount(RequirementsCount),
InheritanceCount(InheritanceCount),
Kind(MergeableWithType ? MergeGroupKind::MergeableWithTypeDef :
MergeGroupKind::UnmergeableWithTypeDef) {
Members.push_back(Info);
}
void removeUnfavored(const NominalTypeDecl *Target) {
Members.erase(std::remove_if(Members.begin(), Members.end(),
[&](SynthesizedExtensionInfo *Info){
return !isExtensionFavored(Target, Info->Ext);}), Members.end());
}
void sortMembers() {
std::sort(Members.begin(), Members.end(),
[](SynthesizedExtensionInfo *LHS, SynthesizedExtensionInfo *RHS) {
return (*LHS) < (*RHS);
});
}
bool operator< (const ExtensionMergeGroup& Rhs) const {
if (RequirementsCount == Rhs.RequirementsCount)
return InheritanceCount < Rhs.InheritanceCount;
return RequirementsCount < Rhs.RequirementsCount;
}
};
typedef std::vector<ExtensionMergeGroup> MergeGroupVector;
NominalTypeDecl *Target;
Type BaseType;
DeclContext *DC;
bool IncludeUnconditional;
PrintOptions Options;
MergeGroupVector AllGroups;
std::unique_ptr<ExtensionInfoMap> InfoMap;
Implementation(NominalTypeDecl *Target,
bool IncludeUnconditional,
PrintOptions Options):
Target(Target),
BaseType(Target->getDeclaredInterfaceType()),
DC(Target),
IncludeUnconditional(IncludeUnconditional),
Options(Options), AllGroups(MergeGroupVector()),
InfoMap(collectSynthesizedExtensionInfo(AllGroups)) {}
unsigned countInherits(ExtensionDecl *ED) {
unsigned Count = 0;
for (auto TL : ED->getInherited()) {
if (shouldPrint(TL.getType()->getAnyNominal(), Options))
Count ++;
}
return Count;
}
std::pair<SynthesizedExtensionInfo, ExtensionMergeInfo>
isApplicable(ExtensionDecl *Ext, bool IsSynthesized) {
SynthesizedExtensionInfo Result(IsSynthesized);
ExtensionMergeInfo MergeInfo;
MergeInfo.HasDocComment = !Ext->getRawComment().isEmpty();
MergeInfo.InheritsCount = countInherits(Ext);
if (!Ext->isConstrainedExtension()) {
if (IncludeUnconditional)
Result.Ext = Ext;
return {Result, MergeInfo};
}
// Get the substitutions from the generic signature of
// the extension to the interface types of the base type's
// declaration.
TypeSubstitutionMap subMap;
if (!BaseType->isAnyExistentialType())
subMap = BaseType->getMemberSubstitutions(Ext);
auto *M = DC->getParentModule();
assert(Ext->getGenericSignature() && "No generic signature.");
for (auto Req : Ext->getGenericSignature()->getRequirements()) {
auto Kind = Req.getKind();
Type First = Req.getFirstType().subst(
M, subMap, SubstOptions());
Type Second = Req.getSecondType().subst(
M, subMap, SubstOptions());
if (!First || !Second) {
// Substitution with interface type bases can only fail
// if a concrete type fails to conform to a protocol.
// In this case, just give up on the extension altogether.
return {Result, MergeInfo};
}
First = First->getCanonicalType();
Second = Second->getCanonicalType();
switch (Kind) {
case RequirementKind::Conformance:
case RequirementKind::Superclass:
if (!canPossiblyConvertTo(First, Second, *DC))
return {Result, MergeInfo};
else if (!isConvertibleTo(First, Second, *DC))
MergeInfo.addRequirement(First, Second, Kind);
break;
case RequirementKind::SameType:
if (!canPossiblyEqual(First, Second, *DC)) {
return {Result, MergeInfo};
} else if (!First->isEqual(Second)) {
MergeInfo.addRequirement(First, Second, Kind);
}
break;
}
}
Result.Ext = Ext;
return {Result, MergeInfo};
}
void populateMergeGroup(ExtensionInfoMap &InfoMap,
ExtensionMergeInfoMap &MergeInfoMap,
MergeGroupVector &Results,
bool AllowMergeWithDefBody) {
for (auto &Pair : InfoMap) {
ExtensionDecl *ED = Pair.first;
ExtensionMergeInfo &MergeInfo = MergeInfoMap[ED];
SynthesizedExtensionInfo &ExtInfo = InfoMap[ED];
auto Found = std::find_if(Results.begin(), Results.end(),
[&](ExtensionMergeGroup &Group) {
return MergeInfo == MergeInfoMap[Group.Members.front()->Ext];
});
if (Found == Results.end()) {
Results.push_back({&ExtInfo,
(unsigned)MergeInfo.Requirements.size(),
MergeInfo.InheritsCount,
AllowMergeWithDefBody && MergeInfo.isMergeableWithTypeDef()});
} else {
Found->Members.push_back(&ExtInfo);
}
}
}
std::unique_ptr<ExtensionInfoMap>
collectSynthesizedExtensionInfoForProtocol(MergeGroupVector &AllGroups) {
std::unique_ptr<ExtensionInfoMap> InfoMap(new ExtensionInfoMap());
ExtensionMergeInfoMap MergeInfoMap;
for (auto *E : Target->getExtensions()) {
if (!shouldPrint(E, Options))
continue;
auto Pair = isApplicable(E, /*Synthesized*/false);
if (Pair.first) {
InfoMap->insert({E, Pair.first});
MergeInfoMap.insert({E, Pair.second});
}
}
populateMergeGroup(*InfoMap, MergeInfoMap, AllGroups,
/*AllowMergeWithDefBody*/false);
std::sort(AllGroups.begin(), AllGroups.end());
for (auto &Group : AllGroups) {
Group.sortMembers();
}
return InfoMap;
}
static bool isEnumRawType(const Decl* D, TypeLoc TL) {
assert (TL.getType());
if (auto ED = dyn_cast<EnumDecl>(D)) {
return ED->hasRawType() && ED->getRawType()->isEqual(TL.getType());
}
return false;
}
std::unique_ptr<ExtensionInfoMap>
collectSynthesizedExtensionInfo(MergeGroupVector &AllGroups) {
if (Target->getKind() == DeclKind::Protocol) {
return collectSynthesizedExtensionInfoForProtocol(AllGroups);
}
std::unique_ptr<ExtensionInfoMap> InfoMap(new ExtensionInfoMap());
ExtensionMergeInfoMap MergeInfoMap;
std::vector<NominalTypeDecl*> Unhandled;
auto addTypeLocNominal = [&](TypeLoc TL) {
if (TL.getType()) {
if (auto D = TL.getType()->getAnyNominal()) {
Unhandled.push_back(D);
}
}
};
for (auto TL : Target->getInherited()) {
if (!isEnumRawType(Target, TL))
addTypeLocNominal(TL);
}
while (!Unhandled.empty()) {
NominalTypeDecl* Back = Unhandled.back();
Unhandled.pop_back();
for (ExtensionDecl *E : Back->getExtensions()) {
if (!shouldPrint(E, Options))
continue;
auto Pair = isApplicable(E, /*Synthesized*/true);
if (Pair.first) {
InfoMap->insert({E, Pair.first});
MergeInfoMap.insert({E, Pair.second});
}
for (auto TL : Back->getInherited()) {
if (!isEnumRawType(Target, TL))
addTypeLocNominal(TL);
}
}
}
// Merge with actual extensions.
for (auto *E : Target->getExtensions()) {
if (!shouldPrint(E, Options))
continue;
auto Pair = isApplicable(E, /*Synthesized*/false);
if (Pair.first) {
InfoMap->insert({E, Pair.first});
MergeInfoMap.insert({E, Pair.second});
}
}
populateMergeGroup(*InfoMap, MergeInfoMap, AllGroups,
/*AllowMergeWithDefBody*/true);
std::sort(AllGroups.begin(), AllGroups.end());
for (auto &Group : AllGroups) {
Group.removeUnfavored(Target);
Group.sortMembers();
}
AllGroups.erase(std::remove_if(AllGroups.begin(), AllGroups.end(),
[](ExtensionMergeGroup &Group) { return Group.Members.empty(); }),
AllGroups.end());
return InfoMap;
}
};
SynthesizedExtensionAnalyzer::
SynthesizedExtensionAnalyzer(NominalTypeDecl *Target,
PrintOptions Options,
bool IncludeUnconditional):
Impl(*(new Implementation(Target, IncludeUnconditional, Options))) {}
SynthesizedExtensionAnalyzer::~SynthesizedExtensionAnalyzer() {delete &Impl;}
bool SynthesizedExtensionAnalyzer::
isInSynthesizedExtension(const ValueDecl *VD) {
if (auto Ext = dyn_cast_or_null<ExtensionDecl>(VD->getDeclContext()->
getInnermostTypeContext())) {
return Impl.InfoMap->count(Ext) != 0 &&
Impl.InfoMap->find(Ext)->second.IsSynthesized;
}
return false;
}
void SynthesizedExtensionAnalyzer::
forEachExtensionMergeGroup(MergeGroupKind Kind, ExtensionGroupOperation Fn) {
for (auto &Group : Impl.AllGroups) {
if (Kind != MergeGroupKind::All) {
if (Kind != Group.Kind)
continue;
}
std::vector<ExtensionAndIsSynthesized> GroupContent;
for (auto &Member : Group.Members) {
GroupContent.push_back({Member->Ext, Member->IsSynthesized});
}
Fn(llvm::makeArrayRef(GroupContent));
}
}
bool SynthesizedExtensionAnalyzer::
hasMergeGroup(MergeGroupKind Kind) {
for (auto &Group : Impl.AllGroups) {
if (Kind == MergeGroupKind::All)
return true;
if (Kind == Group.Kind)
return true;
}
return false;
}
}
PrintOptions PrintOptions::printTypeInterface(Type T) {
PrintOptions result = printInterface();
result.PrintExtensionFromConformingProtocols = true;
result.TransformContext = TypeTransformContext(T);
result.printExtensionContentAsMembers = [T](const ExtensionDecl *ED) {
return isExtensionApplied(*T->getNominalOrBoundGenericNominal()->
getDeclContext(), T, ED);
};
return result;
}
void PrintOptions::setBaseType(Type T) {
TransformContext = TypeTransformContext(T);
}
void PrintOptions::initForSynthesizedExtension(NominalTypeDecl *D) {
TransformContext = TypeTransformContext(D);
}
void PrintOptions::clearSynthesizedExtension() {
TransformContext.reset();
}
TypeTransformContext::TypeTransformContext(Type T)
: BaseType(T.getPointer()) {}
TypeTransformContext::TypeTransformContext(NominalTypeDecl *NTD)
: BaseType(NTD->getDeclaredTypeInContext().getPointer()), Nominal(NTD) {}
NominalTypeDecl *TypeTransformContext::getNominal() const {
return Nominal;
}
Type TypeTransformContext::getBaseType() const {
return Type(BaseType);
}
bool TypeTransformContext::isPrintingSynthesizedExtension() const {
return Nominal != nullptr;
}
std::string ASTPrinter::sanitizeUtf8(StringRef Text) {
llvm::SmallString<256> Builder;
Builder.reserve(Text.size());
const UTF8* Data = reinterpret_cast<const UTF8*>(Text.begin());
const UTF8* End = reinterpret_cast<const UTF8*>(Text.end());
StringRef Replacement = "\ufffd";
while (Data < End) {
auto Step = getNumBytesForUTF8(*Data);
if (Data + Step > End) {
Builder.append(Replacement);
break;
}
if (isLegalUTF8Sequence(Data, Data + Step)) {
Builder.append(Data, Data + Step);
} else {
// If malformed, add replacement characters.
Builder.append(Replacement);
}
Data += Step;
}
return Builder.str();
}
ValueDecl* ASTPrinter::findConformancesWithDocComment(ValueDecl *VD) {
assert(VD->getRawComment().isEmpty());
std::queue<ValueDecl*> AllConformances;
AllConformances.push(VD);
while (!AllConformances.empty()) {
auto *VD = AllConformances.front();
AllConformances.pop();
if (VD->getRawComment().isEmpty()) {
for (auto *Req : VD->getSatisfiedProtocolRequirements()) {
AllConformances.push(Req);
}
} else {
return VD;
}
}
return nullptr;
}
void ASTPrinter::anchor() {}
void ASTPrinter::printIndent() {
llvm::SmallString<16> Str;
for (unsigned i = 0; i != CurrentIndentation; ++i)
Str += ' ';
printText(Str);
}
void ASTPrinter::printTextImpl(StringRef Text) {
forceNewlines();
printText(Text);
}
void ASTPrinter::printTypeRef(Type T, const TypeDecl *RefTo, Identifier Name) {
PrintNameContext Context = PrintNameContext::Normal;
if (isa<GenericTypeParamDecl>(RefTo)) {
Context = PrintNameContext::GenericParameter;
} else if (T && T->is<DynamicSelfType>()) {
assert(T->castTo<DynamicSelfType>()->getSelfType()->getAnyNominal() &&
"protocol Self handled as GenericTypeParamDecl");
Context = PrintNameContext::ClassDynamicSelf;
}
printName(Name, Context);
}
void ASTPrinter::printModuleRef(ModuleEntity Mod, Identifier Name) {
printName(Name);
}
void ASTPrinter::callPrintDeclPre(const Decl *D,
Optional<BracketOptions> Bracket) {
forceNewlines();
if (SynthesizeTarget && D->getKind() == DeclKind::Extension)
printSynthesizedExtensionPre(cast<ExtensionDecl>(D), SynthesizeTarget, Bracket);
else
printDeclPre(D, Bracket);
}
ASTPrinter &ASTPrinter::operator<<(unsigned long long N) {
llvm::SmallString<32> Str;
llvm::raw_svector_ostream OS(Str);
OS << N;
printTextImpl(OS.str());
return *this;
}
ASTPrinter &ASTPrinter::operator<<(UUID UU) {
llvm::SmallString<UUID::StringBufferSize> Str;
UU.toString(Str);
printTextImpl(Str);
return *this;
}
ASTPrinter &ASTPrinter::operator<<(DeclName name) {
llvm::SmallString<32> str;
llvm::raw_svector_ostream os(str);
name.print(os);
printTextImpl(os.str());
return *this;
}
ASTPrinter &operator<<(ASTPrinter &printer, tok keyword) {
StringRef name;
switch (keyword) {
#define KEYWORD(KW) case tok::kw_##KW: name = #KW; break;
#define POUND_KEYWORD(KW) case tok::pound_##KW: name = "#"#KW; break;
#include "swift/Parse/Tokens.def"
default:
llvm_unreachable("unexpected keyword kind");
}
printer.printKeyword(name);
return printer;
}
/// Determine whether to escape the given keyword in the given context.
static bool escapeKeywordInContext(StringRef keyword, PrintNameContext context){
switch (context) {
case PrintNameContext::Normal:
case PrintNameContext::Attribute:
return true;
case PrintNameContext::Keyword:
return false;
case PrintNameContext::ClassDynamicSelf:
case PrintNameContext::GenericParameter:
return keyword != "Self";
case PrintNameContext::FunctionParameterExternal:
case PrintNameContext::FunctionParameterLocal:
case PrintNameContext::TupleElement:
return !canBeArgumentLabel(keyword);
}
}
void ASTPrinter::printName(Identifier Name, PrintNameContext Context) {
callPrintNamePre(Context);
if (Name.empty()) {
*this << "_";
printNamePost(Context);
return;
}
bool IsKeyword = llvm::StringSwitch<bool>(Name.str())
#define KEYWORD(KW) \
.Case(#KW, true)
#include "swift/Parse/Tokens.def"
.Default(false);
if (IsKeyword)
IsKeyword = escapeKeywordInContext(Name.str(), Context);
if (IsKeyword)
*this << "`";
*this << Name.str();
if (IsKeyword)
*this << "`";
printNamePost(Context);
}
void StreamPrinter::printText(StringRef Text) {
OS << Text;
}
/// Whether we will be printing a TypeLoc by using the TypeRepr printer
static bool willUseTypeReprPrinting(TypeLoc tyLoc,
Type currentType,
PrintOptions options) {
// Special case for when transforming archetypes
if (currentType && tyLoc.getType())
return false;
return ((options.PreferTypeRepr && tyLoc.hasLocation()) ||
(tyLoc.getType().isNull() && tyLoc.getTypeRepr()));
}
namespace {
/// \brief AST pretty-printer.
class PrintAST : public ASTVisitor<PrintAST> {
ASTPrinter &Printer;
PrintOptions Options;
unsigned IndentLevel = 0;
Decl *Current = nullptr;
Type CurrentType;
friend DeclVisitor<PrintAST>;
/// \brief RAII object that increases the indentation level.
class IndentRAII {
PrintAST &Self;
bool DoIndent;
public:
IndentRAII(PrintAST &self, bool DoIndent = true)
: Self(self), DoIndent(DoIndent) {
if (DoIndent)
Self.IndentLevel += Self.Options.Indent;
}
~IndentRAII() {
if (DoIndent)
Self.IndentLevel -= Self.Options.Indent;
}
};
/// \brief Indent the current number of indentation spaces.
void indent() {
Printer.setIndent(IndentLevel);
}
/// \brief Record the location of this declaration, which is about to
/// be printed, marking the name and signature end locations.
template<typename FnTy>
void recordDeclLoc(Decl *decl, const FnTy &NameFn,
llvm::function_ref<void()> ParamFn = []{}) {
Printer.callPrintDeclLoc(decl);
NameFn();
Printer.printDeclNameEndLoc(decl);
ParamFn();
Printer.printDeclNameOrSignatureEndLoc(decl);
}
void printSourceRange(CharSourceRange Range, ASTContext &Ctx) {
Printer << Ctx.SourceMgr.extractText(Range);
}
void printClangDocumentationComment(const clang::Decl *D) {
const auto &ClangContext = D->getASTContext();
const clang::RawComment *RC = ClangContext.getRawCommentForAnyRedecl(D);
if (!RC)
return;
bool Invalid;
unsigned StartLocCol =
ClangContext.getSourceManager().getSpellingColumnNumber(
RC->getLocStart(), &Invalid);
if (Invalid)
StartLocCol = 0;
unsigned WhitespaceToTrim = StartLocCol ? StartLocCol - 1 : 0;
SmallVector<StringRef, 8> Lines;
StringRef RawText =
RC->getRawText(ClangContext.getSourceManager()).rtrim("\n\r");
trimLeadingWhitespaceFromLines(RawText, WhitespaceToTrim, Lines);
for (auto Line : Lines) {
Printer << ASTPrinter::sanitizeUtf8(Line);
Printer.printNewline();
}
}
void printRawComment(RawComment RC) {
indent();
SmallVector<StringRef, 8> Lines;
for (const auto &SRC : RC.Comments) {
Lines.clear();
StringRef RawText = SRC.RawText.rtrim("\n\r");
unsigned WhitespaceToTrim = SRC.StartColumn - 1;
trimLeadingWhitespaceFromLines(RawText, WhitespaceToTrim, Lines);
for (auto Line : Lines) {
Printer << Line;
Printer.printNewline();
}
}
}
void printSwiftDocumentationComment(const Decl *D) {
auto RC = D->getRawComment();
if (RC.isEmpty() && !Options.ElevateDocCommentFromConformance)
return;
if (RC.isEmpty()) {
if (auto *VD = dyn_cast<ValueDecl>(D)) {
if (auto *Req = ASTPrinter::findConformancesWithDocComment(
const_cast<ValueDecl*>(VD))) {
printRawComment(Req->getRawComment());
}
}
} else {
printRawComment(RC);
}
}
void printDocumentationComment(const Decl *D) {
if (!Options.PrintDocumentationComments)
return;
// Try to print a comment from Clang.
auto MaybeClangNode = D->getClangNode();
if (MaybeClangNode) {
if (auto *CD = MaybeClangNode.getAsDecl())
printClangDocumentationComment(CD);
return;
}
printSwiftDocumentationComment(D);
}
void printStaticKeyword(StaticSpellingKind StaticSpelling) {
switch (StaticSpelling) {
case StaticSpellingKind::None:
llvm_unreachable("should not be called for non-static decls");
case StaticSpellingKind::KeywordStatic:
Printer << tok::kw_static << " ";
break;
case StaticSpellingKind::KeywordClass:
Printer << tok::kw_class << " ";
break;
}
}
void printAccessibility(Accessibility access, StringRef suffix = "") {
switch (access) {
case Accessibility::Private:
Printer << tok::kw_private;
break;
case Accessibility::FilePrivate:
Printer << tok::kw_fileprivate;
break;
case Accessibility::Internal:
if (!Options.PrintInternalAccessibilityKeyword)
return;
Printer << tok::kw_internal;
break;
case Accessibility::Public:
Printer << tok::kw_public;
break;
case Accessibility::Open:
Printer.printKeyword("open");
break;
}
Printer << suffix << " ";
}
void printAccessibility(const ValueDecl *D) {
if (!Options.PrintAccessibility || !D->hasAccessibility() ||
D->getAttrs().hasAttribute<AccessibilityAttr>())
return;
printAccessibility(D->getFormalAccess());
if (auto storageDecl = dyn_cast<AbstractStorageDecl>(D)) {
if (auto setter = storageDecl->getSetter()) {
Accessibility setterAccess = setter->getFormalAccess();
if (setterAccess != D->getFormalAccess())
printAccessibility(setterAccess, "(set)");
}
}
}
void printType(Type T) {
if (Options.TransformContext) {
// FIXME: it's not clear exactly what we want to keep from the existing
// options, and what we want to discard.
PrintOptions FreshOptions;
FreshOptions.ExcludeAttrList = Options.ExcludeAttrList;
FreshOptions.ExclusiveAttrList = Options.ExclusiveAttrList;
T.print(Printer, FreshOptions);
return;
}
T.print(Printer, Options);
}
void printTransformedType(Type T) {
if (CurrentType) {
if (T->hasArchetype()) {
// Get the interface type, since TypeLocs still have
// contextual types in them.
T = ArchetypeBuilder::mapTypeOutOfContext(
Current->getInnermostDeclContext(), T);
}
// Get the innermost nominal type context.
DeclContext *DC;
if (isa<NominalTypeDecl>(Current))
DC = Current->getInnermostDeclContext();
else
DC = Current->getDeclContext();
// Get the substitutions from our base type.
auto subMap = CurrentType->getMemberSubstitutions(DC);
auto *M = DC->getParentModule();
T = T.subst(M, subMap, SubstFlags::DesugarMemberTypes);
}
printType(T);
}
void printTypeLoc(const TypeLoc &TL) {
if (CurrentType && TL.getType()) {
printTransformedType(TL.getType());
return;
}
// Print a TypeRepr if instructed to do so by options, or if the type
// is null.
if (willUseTypeReprPrinting(TL, CurrentType, Options)) {
if (auto repr = TL.getTypeRepr()) {
llvm::SaveAndRestore<bool> SPTA(Options.SkipParameterTypeAttributes,
true);
repr->print(Printer, Options);
}
return;
}
TL.getType().print(Printer, Options);
}
void printAttributes(const Decl *D);
void printTypedPattern(const TypedPattern *TP);
public:
void printPattern(const Pattern *pattern);
enum GenericSignatureFlags {
PrintParams = 1,
PrintRequirements = 2,
InnermostOnly = 4,
SkipSelfRequirement = 8,
};
void printGenericSignature(const GenericSignature *genericSig,
unsigned flags);
void printSingleDepthOfGenericSignature(
ArrayRef<GenericTypeParamType *> genericParams,
ArrayRef<Requirement> requirements,
unsigned flags);
void printRequirement(const Requirement &req);
private:
bool shouldPrint(const Decl *D, bool Notify = false);
bool shouldPrintPattern(const Pattern *P);
void printPatternType(const Pattern *P);
void printAccessors(AbstractStorageDecl *ASD);
void printMembersOfDecl(Decl * NTD, bool needComma = false,
bool openBracket = true, bool closeBracket = true);
void printMembers(ArrayRef<Decl *> members, bool needComma = false,
bool openBracket = true, bool closeBracket = true);
void printNominalDeclGenericParams(NominalTypeDecl *decl);
void printNominalDeclGenericRequirements(NominalTypeDecl *decl);
void printInherited(const Decl *decl,
ArrayRef<TypeLoc> inherited,
ArrayRef<ProtocolDecl *> protos,
Type superclass = {},
bool explicitClass = false,
bool PrintAsProtocolComposition = false);
void printInherited(const NominalTypeDecl *decl,
bool explicitClass = false);
void printInherited(const EnumDecl *D);
void printInherited(const ExtensionDecl *decl);
void printInherited(const GenericTypeParamDecl *D);
void printEnumElement(EnumElementDecl *elt);
/// \returns true if anything was printed.
bool printASTNodes(const ArrayRef<ASTNode> &Elements, bool NeedIndent = true);
void printOneParameter(const ParamDecl *param, ParameterTypeFlags paramFlags,
bool Curried, bool ArgNameIsAPIByDefault);
void printParameterList(ParameterList *PL, Type paramListTy, bool isCurried,
std::function<bool()> isAPINameByDefault);
/// \brief Print the function parameters in curried or selector style,
/// to match the original function declaration.
void printFunctionParameters(AbstractFunctionDecl *AFD);
#define DECL(Name,Parent) void visit##Name##Decl(Name##Decl *decl);
#define ABSTRACT_DECL(Name, Parent)
#define DECL_RANGE(Name,Start,End)
#include "swift/AST/DeclNodes.def"
#define STMT(Name, Parent) void visit##Name##Stmt(Name##Stmt *stmt);
#include "swift/AST/StmtNodes.def"
void printSynthesizedExtension(NominalTypeDecl* Decl,
ExtensionDecl* ExtDecl);
void printExtension(ExtensionDecl* ExtDecl);
public:
PrintAST(ASTPrinter &Printer, const PrintOptions &Options)
: Printer(Printer), Options(Options) {
if (Options.TransformContext)
CurrentType = Options.TransformContext->getBaseType();
}
using ASTVisitor::visit;
bool visit(Decl *D) {
if (!shouldPrint(D, true))
return false;
Decl *Old = Current;
Current = D;
SWIFT_DEFER { Current = Old; };
Type OldType = CurrentType;
if (CurrentType && (Old != nullptr || Options.PrintAsMember)) {
if (auto *NTD = dyn_cast<NominalTypeDecl>(D)) {
CurrentType = CurrentType->getTypeOfMember(
Options.CurrentModule, NTD, nullptr);
}
}
SWIFT_DEFER { CurrentType = OldType; };
bool Synthesize =
Options.TransformContext &&
Options.TransformContext->isPrintingSynthesizedExtension() &&