forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ASTPrinter.cpp
3424 lines (2993 loc) · 96.8 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 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements printing for the Swift ASTs.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ArchetypeBuilder.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Expr.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.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/Fallthrough.h"
#include "swift/Basic/PrimitiveParsing.h"
#include "swift/Basic/STLExtras.h"
#include "swift/Parse/Lexer.h"
#include "swift/Config.h"
#include "swift/Sema/CodeCompletionTypeChecking.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Decl.h"
#include "clang/Basic/Module.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/SaveAndRestore.h"
#include <algorithm>
using namespace swift;
namespace swift {
class PrinterArchetypeTransformer {
Type BaseTy;
DeclContext *DC;
llvm::DenseMap<TypeBase *, Type> Cache;
llvm::DenseMap<StringRef, Type> IdMap;
public:
PrinterArchetypeTransformer(Type Ty, DeclContext *DC) :
BaseTy(Ty->getRValueType()), DC(DC){
(void) this->DC;
auto D = BaseTy->getNominalOrBoundGenericNominal();
if (!D || !D->getGenericParams())
return;
SmallVector<Type, 3> Scrach;
auto Args = BaseTy->getAllGenericArgs(Scrach);
const auto ParamDecls = D->getGenericParams()->getParams();
assert(ParamDecls.size() == Args.size());
// Map type parameter names with their instantiating arguments.
for(unsigned I = 0, N = ParamDecls.size(); I < N; I ++) {
IdMap[ParamDecls[I]->getName().str()] = Args[I];
}
}
Type transformByName(Type Ty) {
if (Ty->getKind() != TypeKind::Archetype)
return Ty;
// First, we try to find the map from cache.
if (Cache.count(Ty.getPointer()) > 0) {
return Cache[Ty.getPointer()];
}
auto Id = cast<ArchetypeType>(Ty.getPointer())->getName().str();
auto Result = Ty;
// Iterate the IdMap to find the argument type of the given param name.
for (auto It = IdMap.begin(); It != IdMap.end(); ++ It) {
if (Id == It->getFirst()) {
Result = It->getSecond();
break;
}
}
// Put the result into cache.
Cache[Ty.getPointer()] = Result;
return Result;
}
};
}
PrintOptions PrintOptions::printTypeInterface(Type T, DeclContext *DC) {
PrintOptions result = printInterface();
result.pTransformer = std::make_shared<PrinterArchetypeTransformer>(T, DC);
result.TypeToPrint = T.getPointer();
return result;
}
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 malformatted, add replacement characters.
Builder.append(Replacement);
}
Data += Step;
}
return Builder.str();
}
bool ASTPrinter::printTypeInterface(Type Ty, DeclContext *DC,
llvm::raw_ostream &OS) {
if (!Ty)
return false;
Ty = Ty->getRValueType();
PrintOptions Options = PrintOptions::printTypeInterface(Ty.getPointer(), DC);
if (auto ND = Ty->getNominalOrBoundGenericNominal()) {
Options.printExtensionContentAsMembers = [&](const ExtensionDecl *ED) {
return isExtensionApplied(*ND->getDeclContext(), Ty, ED);
};
ND->print(OS, Options);
return true;
}
return false;
}
bool ASTPrinter::printTypeInterface(Type Ty, DeclContext *DC, std::string &Buffer) {
llvm::raw_string_ostream OS(Buffer);
auto Result = printTypeInterface(Ty, DC, OS);
OS.str();
return Result;
}
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) {
if (PendingNewlines != 0) {
llvm::SmallString<16> Str;
for (unsigned i = 0; i != PendingNewlines; ++i)
Str += '\n';
PendingNewlines = 0;
printText(Str);
printIndent();
}
const Decl *PreD = PendingDeclPreCallback;
const Decl *LocD = PendingDeclLocCallback;
PendingDeclPreCallback = nullptr;
PendingDeclLocCallback = nullptr;
if (PreD) {
printDeclPre(PreD);
}
if (LocD) {
printDeclLoc(LocD);
}
printText(Text);
}
void ASTPrinter::printTypeRef(const TypeDecl *TD, Identifier Name) {
PrintNameContext Context = PrintNameContext::Normal;
if (auto GP = dyn_cast<GenericTypeParamDecl>(TD)) {
if (GP->isProtocolSelf())
Context = PrintNameContext::GenericParameter;
}
printName(Name, Context);
}
void ASTPrinter::printModuleRef(ModuleEntity Mod, Identifier Name) {
printName(Name);
}
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;
}
/// Determine whether to escape the given keyword in the given context.
static bool escapeKeywordInContext(StringRef keyword, PrintNameContext context){
switch (context) {
case PrintNameContext::Normal:
return true;
case PrintNameContext::GenericParameter:
return keyword != "Self";
}
}
void ASTPrinter::printName(Identifier Name, PrintNameContext Context) {
if (Name.empty()) {
*this << "_";
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 << "`";
}
void StreamPrinter::printText(StringRef Text) {
OS << Text;
}
namespace {
/// \brief AST pretty-printer.
class PrintAST : public ASTVisitor<PrintAST> {
ASTPrinter &Printer;
PrintOptions Options;
unsigned IndentLevel = 0;
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.
template<typename FnTy>
void recordDeclLoc(Decl *decl, const FnTy &Fn) {
Printer.callPrintDeclLoc(decl);
Fn();
Printer.printDeclNameEndLoc(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;
if (!Options.PrintRegularClangComments) {
Printer.printNewline();
indent();
}
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 printSwiftDocumentationComment(const Decl *D) {
auto RC = D->getRawComment();
if (RC.isEmpty())
return;
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 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 << "static ";
break;
case StaticSpellingKind::KeywordClass:
Printer<< "class ";
break;
}
}
void printAccessibility(Accessibility access, StringRef suffix = "") {
switch (access) {
case Accessibility::Private:
Printer << "private";
break;
case Accessibility::Internal:
if (!Options.PrintInternalAccessibilityKeyword)
return;
Printer << "internal";
break;
case Accessibility::Public:
Printer << "public";
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 printTypeLoc(const TypeLoc &TL) {
if (Options.pTransformer && TL.getType()) {
if (auto RT = Options.pTransformer->transformByName(TL.getType())) {
PrintOptions FreshOptions;
RT.print(Printer, FreshOptions);
return;
}
}
// Print a TypeRepr if instructed to do so by options, or if the type
// is null.
if ((Options.PreferTypeRepr && TL.hasLocation()) ||
TL.getType().isNull()) {
TL.getTypeRepr()->print(Printer, Options);
return;
}
TL.getType().print(Printer, Options);
}
void printAttributes(const Decl *D);
void printTypedPattern(const TypedPattern *TP,
bool StripOuterSliceType = false);
public:
void printPattern(const Pattern *pattern);
void printGenericParams(GenericParamList *params);
void printWhereClause(ArrayRef<RequirementRepr> requirements);
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);
void printMembers(ArrayRef<Decl *> members, bool needComma = false);
void printNominalDeclName(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 Pattern *BodyPattern,
bool ArgNameIsAPIByDefault,
bool StripOuterSliceType,
bool Curried);
/// \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"
public:
PrintAST(ASTPrinter &Printer, const PrintOptions &Options)
: Printer(Printer), Options(Options) {}
using ASTVisitor::visit;
bool visit(Decl *D) {
if (!shouldPrint(D, true))
return false;
Printer.callPrintDeclPre(D);
ASTVisitor::visit(D);
Printer.printDeclPost(D);
return true;
}
};
} // unnamed namespace
void PrintAST::printAttributes(const Decl *D) {
if (Options.SkipAttributes)
return;
D->getAttrs().print(Printer, Options);
}
void PrintAST::printTypedPattern(const TypedPattern *TP,
bool StripOuterSliceType) {
auto TheTypeLoc = TP->getTypeLoc();
if (TheTypeLoc.hasLocation()) {
// If the outer typeloc is an InOutTypeRepr, print the inout before the
// subpattern.
if (auto *IOT = dyn_cast<InOutTypeRepr>(TheTypeLoc.getTypeRepr())) {
TheTypeLoc = TypeLoc(IOT->getBase());
Type T = TheTypeLoc.getType();
if (T) {
if (auto *IOT = T->getAs<InOutType>()) {
T = IOT->getObjectType();
TheTypeLoc.setType(T);
}
}
Printer << "inout ";
}
printPattern(TP->getSubPattern());
Printer << ": ";
if (StripOuterSliceType) {
Type T = TP->getType();
if (auto *BGT = T->getAs<BoundGenericType>()) {
BGT->getGenericArgs()[0].print(Printer, Options);
return;
}
}
printTypeLoc(TheTypeLoc);
return;
}
Type T = TP->getType();
if (auto *IOT = T->getAs<InOutType>()) {
T = IOT->getObjectType();
Printer << "inout ";
}
printPattern(TP->getSubPattern());
Printer << ": ";
if (StripOuterSliceType) {
if (auto *BGT = T->getAs<BoundGenericType>()) {
BGT->getGenericArgs()[0].print(Printer, Options);
return;
}
}
T.print(Printer, Options);
}
void PrintAST::printPattern(const Pattern *pattern) {
switch (pattern->getKind()) {
case PatternKind::Any:
Printer << "_";
break;
case PatternKind::Named: {
auto named = cast<NamedPattern>(pattern);
recordDeclLoc(named->getDecl(),
[&]{
Printer.printName(named->getBodyName());
});
break;
}
case PatternKind::Paren:
Printer << "(";
printPattern(cast<ParenPattern>(pattern)->getSubPattern());
Printer << ")";
break;
case PatternKind::Tuple: {
Printer << "(";
auto TP = cast<TuplePattern>(pattern);
auto Fields = TP->getElements();
for (unsigned i = 0, e = Fields.size(); i != e; ++i) {
const auto &Elt = Fields[i];
if (i != 0)
Printer << ", ";
if (Elt.hasEllipsis()) {
printTypedPattern(cast<TypedPattern>(Elt.getPattern()),
/*StripOuterSliceType=*/true);
Printer << "...";
} else {
printPattern(Elt.getPattern());
}
if (Elt.getDefaultArgKind() != DefaultArgumentKind::None) {
if (Options.PrintDefaultParameterPlaceholder)
Printer << " = default";
else if (Options.VarInitializers) {
// FIXME: Print initializer here.
}
}
}
Printer << ")";
break;
}
case PatternKind::Typed:
printTypedPattern(cast<TypedPattern>(pattern));
break;
case PatternKind::Is: {
auto isa = cast<IsPattern>(pattern);
Printer << "is ";
isa->getCastTypeLoc().getType().print(Printer, Options);
break;
}
case PatternKind::NominalType: {
auto type = cast<NominalTypePattern>(pattern);
type->getCastTypeLoc().getType().print(Printer, Options);
Printer << "(";
interleave(type->getElements().begin(), type->getElements().end(),
[&](const NominalTypePattern::Element &elt) {
Printer << elt.getPropertyName().str() << ":";
printPattern(elt.getSubPattern());
}, [&] {
Printer << ", ";
});
break;
}
case PatternKind::EnumElement: {
auto elt = cast<EnumElementPattern>(pattern);
// FIXME: Print element expr.
if (elt->hasSubPattern())
printPattern(elt->getSubPattern());
break;
}
case PatternKind::OptionalSome:
printPattern(cast<OptionalSomePattern>(pattern)->getSubPattern());
Printer << '?';
break;
case PatternKind::Bool:
Printer << (cast<BoolPattern>(pattern)->getValue() ? "true" : "false");
break;
case PatternKind::Expr:
// FIXME: Print expr.
break;
case PatternKind::Var:
if (!Options.SkipIntroducerKeywords)
Printer << (cast<VarPattern>(pattern)->isLet() ? "let " : "var ");
printPattern(cast<VarPattern>(pattern)->getSubPattern());
}
}
void PrintAST::printGenericParams(GenericParamList *Params) {
if (!Params)
return;
Printer << "<";
bool IsFirst = true;
SmallVector<Type, 4> Scrach;
if (Options.pTransformer) {
auto ArgArr = Options.TypeToPrint->getAllGenericArgs(Scrach);
for (auto Arg : ArgArr) {
if (IsFirst) {
IsFirst = false;
} else {
Printer << ", ";
}
auto NM = Arg->getAnyNominal();
assert(NM && "Cannot get nominal type.");
Printer << NM->getNameStr();
}
} else {
for (auto GP : Params->getParams()) {
if (IsFirst) {
IsFirst = false;
} else {
Printer << ", ";
}
Printer.printName(GP->getName());
printInherited(GP);
}
printWhereClause(Params->getRequirements());
}
Printer << ">";
}
void PrintAST::printWhereClause(ArrayRef<RequirementRepr> requirements) {
if (requirements.empty())
return;
bool isFirst = true;
for (auto &req : requirements) {
if (req.isInvalid() ||
req.getKind() == RequirementKind::WitnessMarker)
continue;
if (isFirst) {
Printer << " where ";
isFirst = false;
} else {
Printer << ", ";
}
auto asWrittenStr = req.getAsWrittenString();
if (!asWrittenStr.empty()) {
Printer << asWrittenStr;
continue;
}
switch (req.getKind()) {
case RequirementKind::Conformance:
printTypeLoc(req.getSubjectLoc());
Printer << " : ";
printTypeLoc(req.getConstraintLoc());
break;
case RequirementKind::SameType:
printTypeLoc(req.getFirstTypeLoc());
Printer << " == ";
printTypeLoc(req.getSecondTypeLoc());
break;
case RequirementKind::WitnessMarker:
llvm_unreachable("Handled above");
}
}
}
bool swift::shouldPrintPattern(const Pattern *P, PrintOptions &Options) {
bool ShouldPrint = false;
P->forEachVariable([&](VarDecl *VD) {
ShouldPrint |= shouldPrint(VD, Options);
});
return ShouldPrint;
}
bool PrintAST::shouldPrintPattern(const Pattern *P) {
return swift::shouldPrintPattern(P, Options);
}
void PrintAST::printPatternType(const Pattern *P) {
if (P->hasType()) {
Printer << ": ";
P->getType().print(Printer, Options);
}
}
bool swift::shouldPrint(const Decl *D, PrintOptions &Options) {
if (auto *ED= dyn_cast<ExtensionDecl>(D)) {
if (Options.printExtensionContentAsMembers(ED))
return false;
}
if (Options.SkipDeinit && isa<DestructorDecl>(D)) {
return false;
}
if (Options.SkipImports && isa<ImportDecl>(D)) {
return false;
}
if (Options.SkipImplicit && D->isImplicit())
return false;
if (Options.SkipUnavailable &&
D->getAttrs().isUnavailable(D->getASTContext()))
return false;
// Skip declarations that are not accessible.
if (auto *VD = dyn_cast<ValueDecl>(D)) {
if (Options.AccessibilityFilter > Accessibility::Private &&
VD->hasAccessibility() &&
VD->getFormalAccess() < Options.AccessibilityFilter)
return false;
}
if (Options.SkipPrivateStdlibDecls &&
D->isPrivateStdlibDecl(
/*whitelistProtocols=*/!Options.SkipUnderscoredStdlibProtocols))
return false;
if (Options.SkipEmptyExtensionDecls && isa<ExtensionDecl>(D)) {
auto Ext = cast<ExtensionDecl>(D);
// If the extension doesn't add protocols or has no members that we should
// print then skip printing it.
if (Ext->getLocalProtocols().empty()) {
bool HasMemberToPrint = false;
for (auto Member : Ext->getMembers()) {
if (shouldPrint(Member, Options)) {
HasMemberToPrint = true;
break;
}
}
if (!HasMemberToPrint)
return false;
}
}
// We need to handle PatternBindingDecl as a special case here because its
// attributes can only be retrieved from the inside VarDecls.
if (auto *PD = dyn_cast<PatternBindingDecl>(D)) {
auto ShouldPrint = false;
for (auto entry : PD->getPatternList()) {
ShouldPrint |= shouldPrintPattern(entry.getPattern(), Options);
if (ShouldPrint)
return true;
}
return false;
}
return true;
}
bool PrintAST::shouldPrint(const Decl *D, bool Notify) {
auto Result = swift::shouldPrint(D, Options);
if (!Result && Notify)
Printer.avoidPrintDeclPost(D);
return Result;
}
static bool isAccessorAssumedNonMutating(FuncDecl *accessor) {
switch (accessor->getAccessorKind()) {
case AccessorKind::IsGetter:
case AccessorKind::IsAddressor:
return true;
case AccessorKind::IsSetter:
case AccessorKind::IsWillSet:
case AccessorKind::IsDidSet:
case AccessorKind::IsMaterializeForSet:
case AccessorKind::IsMutableAddressor:
return false;
case AccessorKind::NotAccessor:
llvm_unreachable("not an addressor!");
}
llvm_unreachable("bad addressor kind");
}
static StringRef getAddressorLabel(FuncDecl *addressor) {
switch (addressor->getAddressorKind()) {
case AddressorKind::NotAddressor:
llvm_unreachable("addressor claims not to be an addressor");
case AddressorKind::Unsafe:
return "unsafeAddress";
case AddressorKind::Owning:
return "addressWithOwner";
case AddressorKind::NativeOwning:
return "addressWithNativeOwner";
case AddressorKind::NativePinning:
return "addressWithPinnedNativeOwner";
}
llvm_unreachable("bad addressor kind");
}
static StringRef getMutableAddressorLabel(FuncDecl *addressor) {
switch (addressor->getAddressorKind()) {
case AddressorKind::NotAddressor:
llvm_unreachable("addressor claims not to be an addressor");
case AddressorKind::Unsafe:
return "unsafeMutableAddress";
case AddressorKind::Owning:
return "mutableAddressWithOwner";
case AddressorKind::NativeOwning:
return "mutableAddressWithNativeOwner";
case AddressorKind::NativePinning:
return "mutableAddressWithPinnedNativeOwner";
}
llvm_unreachable("bad addressor kind");
}
void PrintAST::printAccessors(AbstractStorageDecl *ASD) {
if (isa<VarDecl>(ASD) && !Options.PrintPropertyAccessors)
return;
auto storageKind = ASD->getStorageKind();
// Never print anything for stored properties.
if (storageKind == AbstractStorageDecl::Stored)
return;
// Treat StoredWithTrivialAccessors the same as Stored unless
// we're printing for SIL, in which case we want to distinguish it
// from a pure stored property.
if (storageKind == AbstractStorageDecl::StoredWithTrivialAccessors) {
if (!Options.PrintForSIL) return;
// Don't print an accessor for a let; the parser can't handle it.
if (isa<VarDecl>(ASD) && cast<VarDecl>(ASD)->isLet())
return;
}
// We sometimes want to print the accessors abstractly
// instead of listing out how they're actually implemented.
bool inProtocol = isa<ProtocolDecl>(ASD->getDeclContext());
if (inProtocol ||
(Options.AbstractAccessors && !Options.FunctionDefinitions)) {
bool mutatingGetter = ASD->isGetterMutating();
bool settable = ASD->isSettable(nullptr);
bool nonmutatingSetter = false;
if (settable && ASD->isSetterNonMutating() && ASD->isInstanceMember() &&
!ASD->getDeclContext()->getDeclaredTypeInContext()
->hasReferenceSemantics())
nonmutatingSetter = true;
// We're about to print something like this:
// { mutating? get (nonmutating? set)? }
// But don't print "{ get set }" if we don't have to.
if (!inProtocol && !Options.PrintGetSetOnRWProperties &&
settable && !mutatingGetter && !nonmutatingSetter) {
return;
}
Printer << " {";
if (mutatingGetter) Printer << " mutating";
Printer << " get";
if (settable) {
if (nonmutatingSetter) Printer << " nonmutating";
Printer << " set";
}
Printer << " }";
return;
}
// Honor !Options.PrintGetSetOnRWProperties in the only remaining
// case where we could end up printing { get set }.
if (storageKind == AbstractStorageDecl::StoredWithTrivialAccessors ||
storageKind == AbstractStorageDecl::Computed) {
if (!Options.PrintGetSetOnRWProperties &&
!Options.FunctionDefinitions &&
ASD->getSetter() &&
!ASD->getGetter()->isMutating() &&
!ASD->getSetter()->isExplicitNonMutating()) {
return;
}
}
// Otherwise, print all the concrete defining accessors.
bool PrintAccessorBody = Options.FunctionDefinitions;
auto PrintAccessor = [&](FuncDecl *Accessor, StringRef Label) {
if (!Accessor)
return;
if (!PrintAccessorBody) {
if (isAccessorAssumedNonMutating(Accessor)) {
if (Accessor->isMutating())
Printer << " mutating";
} else {
if (Accessor->isExplicitNonMutating()) {
Printer << " nonmutating";
}
}
Printer << " " << Label;
} else {
Printer.printNewline();
IndentRAII IndentMore(*this);
indent();
visit(Accessor);
}
};
auto PrintAddressor = [&](FuncDecl *accessor) {
if (!accessor) return;
PrintAccessor(accessor, getAddressorLabel(accessor));
};
auto PrintMutableAddressor = [&](FuncDecl *accessor) {
if (!accessor) return;
PrintAccessor(accessor, getMutableAddressorLabel(accessor));
};
Printer << " {";
switch (storageKind) {
case AbstractStorageDecl::Stored:
llvm_unreachable("filtered out above!");
case AbstractStorageDecl::StoredWithTrivialAccessors:
case AbstractStorageDecl::Computed:
PrintAccessor(ASD->getGetter(), "get");
PrintAccessor(ASD->getSetter(), "set");
break;
case AbstractStorageDecl::StoredWithObservers:
case AbstractStorageDecl::InheritedWithObservers:
PrintAccessor(ASD->getWillSetFunc(), "willSet");
PrintAccessor(ASD->getDidSetFunc(), "didSet");
break;
case AbstractStorageDecl::Addressed:
case AbstractStorageDecl::AddressedWithTrivialAccessors:
case AbstractStorageDecl::AddressedWithObservers:
PrintAddressor(ASD->getAddressor());
PrintMutableAddressor(ASD->getMutableAddressor());
if (ASD->hasObservers()) {