forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathASTPrinter.cpp
5955 lines (5156 loc) · 187 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 - 2020 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/ASTMangler.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/Comment.h"
#include "swift/AST/Decl.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/FileUnit.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/PrintOptions.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SILLayout.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/Feature.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Basic/QuotedString.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Config.h"
#include "swift/Parse/Lexer.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/SaveAndRestore.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <queue>
using namespace swift;
// Defined here to avoid repeatedly paying the price of template instantiation.
const std::function<bool(const ExtensionDecl *)>
PrintOptions::defaultPrintExtensionContentAsMembers
= [] (const ExtensionDecl *) { return false; };
void PrintOptions::setBaseType(Type T) {
if (T->is<ErrorType>())
return;
TransformContext = TypeTransformContext(T);
}
void PrintOptions::initForSynthesizedExtension(TypeOrExtensionDecl D) {
TransformContext = TypeTransformContext(D);
}
void PrintOptions::clearSynthesizedExtension() {
TransformContext.reset();
}
static bool isPublicOrUsableFromInline(const ValueDecl *VD) {
AccessScope scope =
VD->getFormalAccessScope(/*useDC*/nullptr,
/*treatUsableFromInlineAsPublic*/true);
return scope.isPublic();
}
static bool isPublicOrUsableFromInline(Type ty) {
// Note the double negative here: we're looking for any referenced decls that
// are *not* public-or-usableFromInline.
return !ty.findIf([](Type typePart) -> bool {
// FIXME: If we have an internal typealias for a non-internal type, we ought
// to be able to print it by desugaring.
if (auto *aliasTy = dyn_cast<TypeAliasType>(typePart.getPointer()))
return !isPublicOrUsableFromInline(aliasTy->getDecl());
if (auto *nominal = typePart->getAnyNominal())
return !isPublicOrUsableFromInline(nominal);
return false;
});
}
static bool contributesToParentTypeStorage(const AbstractStorageDecl *ASD) {
auto *DC = ASD->getDeclContext()->getAsDecl();
if (!DC) return false;
auto *ND = dyn_cast<NominalTypeDecl>(DC);
if (!ND) return false;
return !ND->isResilient() && ASD->hasStorage() && !ASD->isStatic();
}
PrintOptions PrintOptions::printSwiftInterfaceFile(ModuleDecl *ModuleToPrint,
bool preferTypeRepr,
bool printFullConvention,
bool printSPIs) {
PrintOptions result;
result.IsForSwiftInterface = true;
result.PrintLongAttrsOnSeparateLines = true;
result.TypeDefinitions = true;
result.PrintIfConfig = false;
result.CurrentModule = ModuleToPrint;
result.FullyQualifiedTypes = true;
result.FullyQualifiedTypesIfAmbiguous = true;
result.FullyQualifiedExtendedTypesIfAmbiguous = true;
result.UseExportedModuleNames = true;
result.AllowNullTypes = false;
result.SkipImports = true;
result.OmitNameOfInaccessibleProperties = true;
result.FunctionDefinitions = true;
result.CollapseSingleGetterProperty = false;
result.VarInitializers = true;
result.EnumRawValues = EnumRawValueMode::PrintObjCOnly;
result.OpaqueReturnTypePrinting =
OpaqueReturnTypePrintingMode::StableReference;
result.PreferTypeRepr = preferTypeRepr;
if (printFullConvention)
result.PrintFunctionRepresentationAttrs =
PrintOptions::FunctionRepresentationMode::Full;
result.AlwaysTryPrintParameterLabels = true;
result.PrintSPIs = printSPIs;
// We should print __consuming, __owned, etc for the module interface file.
result.SkipUnderscoredKeywords = false;
// We should provide backward-compatible Swift interfaces when we can.
result.PrintCompatibilityFeatureChecks = true;
result.FunctionBody = [](const ValueDecl *decl, ASTPrinter &printer) {
auto AFD = dyn_cast<AbstractFunctionDecl>(decl);
if (!AFD)
return;
if (AFD->getResilienceExpansion() != ResilienceExpansion::Minimal)
return;
if (!AFD->hasInlinableBodyText())
return;
SmallString<128> scratch;
printer << " " << AFD->getInlinableBodyText(scratch);
};
class ShouldPrintForModuleInterface : public ShouldPrintChecker {
bool shouldPrint(const Decl *D, const PrintOptions &options) override {
if (!D)
return false;
// Skip anything that is marked `@_implementationOnly` itself.
if (D->getAttrs().hasAttribute<ImplementationOnlyAttr>())
return false;
// Skip SPI decls if `PrintSPIs`.
if (!options.PrintSPIs && D->isSPI())
return false;
// Skip anything that isn't 'public' or '@usableFromInline'.
if (auto *VD = dyn_cast<ValueDecl>(D)) {
if (!isPublicOrUsableFromInline(VD)) {
// We do want to print private stored properties, without their
// original names present.
if (auto *ASD = dyn_cast<AbstractStorageDecl>(VD))
if (contributesToParentTypeStorage(ASD))
return true;
return false;
}
}
// Skip extensions that extend things we wouldn't print.
if (auto *ED = dyn_cast<ExtensionDecl>(D)) {
if (!shouldPrint(ED->getExtendedNominal(), options))
return false;
// Skip extensions to implementation-only imported types that have
// no public members.
auto localModule = ED->getParentModule();
auto nominalModule = ED->getExtendedNominal()->getParentModule();
if (localModule != nominalModule &&
localModule->isImportedImplementationOnly(nominalModule)) {
bool shouldPrintMembers = llvm::any_of(
ED->getAllMembers(),
[&](const Decl *member) -> bool {
return shouldPrint(member, options);
});
if (!shouldPrintMembers)
return false;
}
for (const Requirement &req : ED->getGenericRequirements()) {
if (!isPublicOrUsableFromInline(req.getFirstType()))
return false;
switch (req.getKind()) {
case RequirementKind::Conformance:
case RequirementKind::Superclass:
case RequirementKind::SameType:
if (!isPublicOrUsableFromInline(req.getSecondType()))
return false;
break;
case RequirementKind::Layout:
break;
}
}
}
// Skip typealiases that just redeclare generic parameters.
if (auto *alias = dyn_cast<TypeAliasDecl>(D)) {
if (alias->isImplicit()) {
const Decl *parent =
D->getDeclContext()->getAsDecl();
if (auto *genericCtx = parent->getAsGenericContext()) {
bool matchesGenericParam =
llvm::any_of(genericCtx->getInnermostGenericParamTypes(),
[alias](const GenericTypeParamType *param) {
return param->getName() == alias->getName();
});
if (matchesGenericParam)
return false;
}
}
}
// Skip stub constructors.
if (auto *ctor = dyn_cast<ConstructorDecl>(D)) {
if (ctor->hasStubImplementation())
return false;
}
return ShouldPrintChecker::shouldPrint(D, options);
}
};
result.CurrentPrintabilityChecker =
std::make_shared<ShouldPrintForModuleInterface>();
// FIXME: We don't really need 'public' on everything; we could just change
// the default to 'public' and mark the 'internal' things.
result.PrintAccess = true;
result.ExcludeAttrList = {
DAK_AccessControl,
DAK_SetterAccess,
DAK_Lazy,
DAK_StaticInitializeObjCMetadata,
DAK_RestatedObjCConformance
};
return result;
}
TypeTransformContext::TypeTransformContext(Type T)
: BaseType(T.getPointer()) {
assert(T->mayHaveMembers());
}
TypeTransformContext::TypeTransformContext(TypeOrExtensionDecl D)
: BaseType(nullptr), Decl(D) {
if (auto NTD = Decl.Decl.dyn_cast<NominalTypeDecl *>())
BaseType = NTD->getDeclaredTypeInContext().getPointer();
else {
auto *ED = Decl.Decl.get<ExtensionDecl *>();
BaseType = ED->getDeclaredTypeInContext().getPointer();
}
}
TypeOrExtensionDecl TypeTransformContext::getDecl() const { return Decl; }
DeclContext *TypeTransformContext::getDeclContext() const {
return Decl.getAsDecl()->getDeclContext();
}
Type TypeTransformContext::getBaseType() const {
return Type(BaseType);
}
bool TypeTransformContext::isPrintingSynthesizedExtension() const {
return !Decl.isNull();
}
std::string ASTPrinter::sanitizeUtf8(StringRef Text) {
llvm::SmallString<256> Builder;
Builder.reserve(Text.size());
const llvm::UTF8* Data = reinterpret_cast<const llvm::UTF8*>(Text.begin());
const llvm::UTF8* End = reinterpret_cast<const llvm::UTF8*>(Text.end());
StringRef Replacement = u8"\ufffd";
while (Data < End) {
auto Step = llvm::getNumBytesForUTF8(*Data);
if (Data + Step > End) {
Builder.append(Replacement);
break;
}
if (llvm::isLegalUTF8Sequence(Data, Data + Step)) {
Builder.append(Data, Data + Step);
} else {
// If malformed, add replacement characters.
Builder.append(Replacement);
}
Data += Step;
}
return std::string(Builder.str());
}
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::printEscapedStringLiteral(StringRef str) {
SmallString<128> encodeBuf;
StringRef escaped =
Lexer::getEncodedStringSegment(str, encodeBuf,
/*isFirstSegment*/true,
/*isLastSegment*/true,
/*indentToStrip*/~0U /* sentinel */);
// FIXME: This is wasteful, but ASTPrinter is an abstract class that doesn't
// have a directly-accessible ostream.
SmallString<128> escapeBuf;
llvm::raw_svector_ostream os(escapeBuf);
os << QuotedString(escaped);
printTextImpl(escapeBuf.str());
}
void ASTPrinter::printTypeRef(Type T, const TypeDecl *RefTo, Identifier Name,
PrintNameContext Context) {
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 && isa<ExtensionDecl>(D))
printSynthesizedExtensionPre(cast<ExtensionDecl>(D), SynthesizeTarget, Bracket);
else
printDeclPre(D, Bracket);
}
ASTPrinter &ASTPrinter::operator<<(QuotedString s) {
llvm::SmallString<32> Str;
llvm::raw_svector_ostream OS(Str);
OS << s;
printTextImpl(OS.str());
return *this;
}
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<<(Identifier name) {
return *this << DeclName(name);
}
ASTPrinter &ASTPrinter::operator<<(DeclBaseName name) {
return *this << DeclName(name);
}
ASTPrinter &ASTPrinter::operator<<(DeclName name) {
llvm::SmallString<32> str;
llvm::raw_svector_ostream os(str);
name.print(os);
printTextImpl(os.str());
return *this;
}
ASTPrinter &ASTPrinter::operator<<(DeclNameRef ref) {
llvm::SmallString<32> str;
llvm::raw_svector_ostream os(str);
ref.print(os);
printTextImpl(os.str());
return *this;
}
llvm::raw_ostream &swift::
operator<<(llvm::raw_ostream &OS, tok keyword) {
switch (keyword) {
#define KEYWORD(KW) case tok::kw_##KW: OS << #KW; break;
#define POUND_KEYWORD(KW) case tok::pound_##KW: OS << "#"#KW; break;
#define PUNCTUATOR(PUN, TEXT) case tok::PUN: OS << TEXT; break;
#include "swift/Syntax/TokenKinds.def"
default:
llvm_unreachable("unexpected keyword or punctuator kind");
}
return OS;
}
uint8_t swift::getKeywordLen(tok keyword) {
switch (keyword) {
#define KEYWORD(KW) case tok::kw_##KW: return StringRef(#KW).size();
#define POUND_KEYWORD(KW) case tok::pound_##KW: return StringRef("#"#KW).size();
#define PUNCTUATOR(PUN, TEXT) case tok::PUN: return StringRef(TEXT).size();
#include "swift/Syntax/TokenKinds.def"
default:
llvm_unreachable("unexpected keyword or punctuator kind");
}
}
StringRef swift::getCodePlaceholder() { return "<#code#>"; }
ASTPrinter &operator<<(ASTPrinter &printer, tok keyword) {
SmallString<16> Buffer;
llvm::raw_svector_ostream OS(Buffer);
OS << keyword;
printer.printKeyword(Buffer.str(), PrintOptions());
return printer;
}
/// Determine whether to escape the given keyword in the given context.
static bool escapeKeywordInContext(StringRef keyword, PrintNameContext context){
bool isKeyword = llvm::StringSwitch<bool>(keyword)
#define KEYWORD(KW) \
.Case(#KW, true)
#include "swift/Syntax/TokenKinds.def"
.Default(false);
switch (context) {
case PrintNameContext::Normal:
case PrintNameContext::Attribute:
return isKeyword;
case PrintNameContext::Keyword:
case PrintNameContext::IntroducerKeyword:
return false;
case PrintNameContext::ClassDynamicSelf:
case PrintNameContext::GenericParameter:
return isKeyword && keyword != "Self";
case PrintNameContext::TypeMember:
return isKeyword || !canBeMemberName(keyword);
case PrintNameContext::FunctionParameterExternal:
case PrintNameContext::FunctionParameterLocal:
case PrintNameContext::TupleElement:
return !canBeArgumentLabel(keyword);
}
llvm_unreachable("Unhandled PrintNameContext in switch.");
}
void ASTPrinter::printName(Identifier Name, PrintNameContext Context) {
callPrintNamePre(Context);
if (Name.empty()) {
*this << "_";
printNamePost(Context);
return;
}
bool shouldEscapeKeyword = escapeKeywordInContext(Name.str(), Context);
if (shouldEscapeKeyword)
*this << "`";
*this << Name.str();
if (shouldEscapeKeyword)
*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,
const 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 {
/// AST pretty-printer.
class PrintAST : public ASTVisitor<PrintAST> {
ASTPrinter &Printer;
PrintOptions Options;
unsigned IndentLevel = 0;
Decl *Current = nullptr;
Type CurrentType;
void setCurrentType(Type NewCurrentType) {
CurrentType = NewCurrentType;
assert(CurrentType.isNull() ||
!CurrentType->hasArchetype() &&
"CurrentType should be an interface type");
}
friend DeclVisitor<PrintAST>;
/// 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;
}
};
/// Indent the current number of indentation spaces.
void indent() {
Printer.setIndent(IndentLevel);
}
/// 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);
}
static std::string sanitizeClangDocCommentStyle(StringRef Line) {
static StringRef ClangStart = "/*!";
static StringRef SwiftStart = "/**";
auto Pos = Line.find(ClangStart);
if (Pos == StringRef::npos)
return Line.str();
StringRef Segment[2];
// The text before "/*!"
Segment[0] = Line.substr(0, Pos);
// The text after "/*!"
Segment[1] = Line.substr(Pos).substr(ClangStart.size());
// Only sanitize when "/*!" appears at the start of this line.
if (Segment[0].trim().empty()) {
return (llvm::Twine(Segment[0]) + SwiftStart + Segment[1]).str();
}
return Line.str();
}
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->getBeginLoc(), &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);
bool FirstLine = true;
for (auto Line : Lines) {
if (FirstLine)
Printer << sanitizeClangDocCommentStyle(ASTPrinter::sanitizeUtf8(Line));
else
Printer << ASTPrinter::sanitizeUtf8(Line);
Printer.printNewline();
FirstLine = false;
}
}
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.ColumnIndent - 1;
trimLeadingWhitespaceFromLines(RawText, WhitespaceToTrim, Lines);
for (auto Line : Lines) {
Printer << Line;
Printer.printNewline();
}
}
}
void printSwiftDocumentationComment(const Decl *D) {
if (Options.CascadeDocComment)
D = getDocCommentProvidingDecl(D);
if (!D)
return;
auto RC = D->getRawComment();
if (RC.isEmpty())
return;
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 printAccess(AccessLevel access, StringRef suffix = "") {
switch (access) {
case AccessLevel::Private:
Printer << tok::kw_private;
break;
case AccessLevel::FilePrivate:
Printer << tok::kw_fileprivate;
break;
case AccessLevel::Internal:
if (!Options.PrintInternalAccessKeyword)
return;
Printer << tok::kw_internal;
break;
case AccessLevel::Public:
Printer << tok::kw_public;
break;
case AccessLevel::Open:
Printer.printKeyword("open", Options);
break;
}
Printer << suffix << " ";
}
void printAccess(const ValueDecl *D) {
assert(!llvm::is_contained(Options.ExcludeAttrList, DAK_AccessControl) ||
llvm::is_contained(Options.ExcludeAttrList, DAK_SetterAccess));
if (!Options.PrintAccess || isa<ProtocolDecl>(D->getDeclContext()))
return;
if (D->getAttrs().hasAttribute<AccessControlAttr>() &&
!llvm::is_contained(Options.ExcludeAttrList, DAK_AccessControl))
return;
printAccess(D->getFormalAccess());
bool shouldSkipSetterAccess =
llvm::is_contained(Options.ExcludeAttrList, DAK_SetterAccess);
if (auto storageDecl = dyn_cast<AbstractStorageDecl>(D)) {
if (auto setter = storageDecl->getAccessor(AccessorKind::Set)) {
AccessLevel setterAccess = setter->getFormalAccess();
if (setterAccess != D->getFormalAccess() && !shouldSkipSetterAccess)
printAccess(setterAccess, "(set)");
}
}
}
void printTypeWithOptions(Type T, const PrintOptions &options) {
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;
FreshOptions.PrintOptionalAsImplicitlyUnwrapped = options.PrintOptionalAsImplicitlyUnwrapped;
FreshOptions.TransformContext = options.TransformContext;
T.print(Printer, FreshOptions);
return;
}
T.print(Printer, options);
}
void printType(Type T) { printTypeWithOptions(T, Options); }
void printTransformedTypeWithOptions(Type T, PrintOptions options) {
if (CurrentType && Current && CurrentType->mayHaveMembers()) {
auto *M = Current->getDeclContext()->getParentModule();
SubstitutionMap subMap;
if (auto *NTD = dyn_cast<NominalTypeDecl>(Current))
subMap = CurrentType->getContextSubstitutionMap(M, NTD);
else if (auto *ED = dyn_cast<ExtensionDecl>(Current))
subMap = CurrentType->getContextSubstitutionMap(M, ED);
else {
Decl *subTarget = Current;
if (isa<ParamDecl>(Current)) {
auto *DC = Current->getDeclContext();
if (auto *FD = dyn_cast<AbstractFunctionDecl>(DC))
subTarget = FD;
}
subMap = CurrentType->getMemberSubstitutionMap(
M, cast<ValueDecl>(subTarget));
}
T = T.subst(subMap, SubstFlags::DesugarMemberTypes);
options.TransformContext = TypeTransformContext(CurrentType);
}
printTypeWithOptions(T, options);
}
void printTransformedType(Type T) {
printTransformedTypeWithOptions(T, Options);
}
void printTypeLocWithOptions(const TypeLoc &TL, const PrintOptions &options) {
if (CurrentType && TL.getType()) {
printTransformedTypeWithOptions(TL.getType(), options);
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())
repr->print(Printer, options);
return;
}
TL.getType().print(Printer, options);
}
void printTypeLoc(const TypeLoc &TL) { printTypeLocWithOptions(TL, Options); }
void printTypeLocForImplicitlyUnwrappedOptional(TypeLoc TL, bool IUO) {
PrintOptions options = Options;
options.PrintOptionalAsImplicitlyUnwrapped = IUO;
printTypeLocWithOptions(TL, options);
}
void printContextIfNeeded(const Decl *decl) {
if (IndentLevel > 0)
return;
switch (Options.ShouldQualifyNestedDeclarations) {
case PrintOptions::QualifyNestedDeclarations::Never:
return;
case PrintOptions::QualifyNestedDeclarations::TypesOnly:
if (!isa<TypeDecl>(decl))
return;
break;
case PrintOptions::QualifyNestedDeclarations::Always:
break;
}
auto *container = dyn_cast<NominalTypeDecl>(decl->getDeclContext());
if (!container)
return;
printType(container->getDeclaredInterfaceType());
Printer << ".";
}
void printAttributes(const Decl *D);
void printTypedPattern(const TypedPattern *TP);
void printBraceStmt(const BraceStmt *stmt, bool newlineIfEmpty = true);
void printAccessorDecl(const AccessorDecl *decl);
public:
void printPattern(const Pattern *pattern);
enum GenericSignatureFlags {
PrintParams = 1,
PrintRequirements = 2,
InnermostOnly = 4,
SwapSelfAndDependentMemberType = 8,
PrintInherited = 16,
};
void printInheritedFromRequirementSignature(ProtocolDecl *proto,
Decl *attachingTo);
void printWhereClauseFromRequirementSignature(ProtocolDecl *proto,
Decl *attachingTo);
void printGenericSignature(GenericSignature genericSig,
unsigned flags);
void
printGenericSignature(GenericSignature genericSig, unsigned flags,
llvm::function_ref<bool(const Requirement &)> filter);
void printSingleDepthOfGenericSignature(
TypeArrayView<GenericTypeParamType> genericParams,
ArrayRef<Requirement> requirements, unsigned flags,
llvm::function_ref<bool(const Requirement &)> filter);
void printSingleDepthOfGenericSignature(
TypeArrayView<GenericTypeParamType> genericParams,
ArrayRef<Requirement> requirements, bool &isFirstReq, unsigned flags,
llvm::function_ref<bool(const Requirement &)> filter);
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(const AbstractStorageDecl *ASD);
void printSelfAccessKindModifiersIfNeeded(const FuncDecl *FD);
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 printGenericDeclGenericParams(GenericContext *decl);
void printDeclGenericRequirements(GenericContext *decl);
void printInherited(const Decl *decl);
void printBodyIfNecessary(const AbstractFunctionDecl *decl);
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 ArgNameIsAPIByDefault);
void printParameterList(ParameterList *PL,
ArrayRef<AnyFunctionType::Param> params,
bool isAPINameByDefault);
/// 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(Type ExtendedType, ExtensionDecl *ExtDecl);
void printExtension(ExtensionDecl* ExtDecl);
void printExtendedTypeName(TypeLoc ExtendedTypeLoc);
public:
PrintAST(ASTPrinter &Printer, const PrintOptions &Options)
: Printer(Printer), Options(Options) {
if (Options.TransformContext) {
Type CurrentType = Options.TransformContext->getBaseType();
if (CurrentType && CurrentType->hasArchetype()) {
// OpenedArchetypeTypes get replaced by a GenericTypeParamType without a
// name in mapTypeOutOfContext. The GenericTypeParamType has no children
// so we can't use it for TypeTransformContext.
// To work around this, replace the OpenedArchetypeType with the type of
// the protocol itself.
CurrentType = CurrentType.transform([](Type T) -> Type {
if (auto *Opened = T->getAs<OpenedArchetypeType>()) {
return Opened->getOpenedExistentialType();
} else {
return T;
}
});
CurrentType = CurrentType->mapTypeOutOfContext();
}
setCurrentType(CurrentType);
}
}
using ASTVisitor::visit;
bool visit(Decl *D) {
#if SWIFT_BUILD_ONLY_SYNTAXPARSERLIB
return false; // not needed for the parser library.
#endif
bool Synthesize =
Options.TransformContext &&
Options.TransformContext->isPrintingSynthesizedExtension() &&
isa<ExtensionDecl>(D);
if (!shouldPrint(D, true) && !Synthesize)
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)) {
auto Subs = CurrentType->getContextSubstitutionMap(
Options.CurrentModule, NTD->getDeclContext());
setCurrentType(NTD->getDeclaredInterfaceType().subst(Subs));
}
}
SWIFT_DEFER { setCurrentType(OldType); };
if (Synthesize) {
Printer.setSynthesizedTarget(Options.TransformContext->getDecl());
}
// We want to print a newline before doc comments. Swift code already
// handles this, but we need to insert it for clang doc comments when not
// printing other clang comments. Do it now so the printDeclPre callback
// happens after the newline.
if (Options.PrintDocumentationComments &&
!Options.PrintRegularClangComments &&
D->hasClangNode()) {
auto clangNode = D->getClangNode();
auto clangDecl = clangNode.getAsDecl();
if (clangDecl &&
clangDecl->getASTContext().getRawCommentForAnyRedecl(clangDecl)) {
Printer.printNewline();
indent();
}
}
Printer.callPrintDeclPre(D, Options.BracketOptions);
bool haveFeatureChecks = Options.PrintCompatibilityFeatureChecks &&
printCompatibilityFeatureChecksPre(Printer, D);
ASTVisitor::visit(D);