forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrintAsObjC.cpp
2394 lines (2065 loc) · 79.2 KB
/
PrintAsObjC.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
//===--- PrintAsObjC.cpp - Emit a header file for a Swift AST -------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
#include "swift/PrintAsObjC/PrintAsObjC.h"
#include "swift/Strings.h"
#include "swift/AST/AST.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/AST/Comment.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/Frontend/Frontend.h"
#include "swift/Frontend/PrintingDiagnosticConsumer.h"
#include "swift/IDE/CommentConversion.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 "llvm/ADT/SetVector.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
using namespace swift;
static bool isNSObjectOrAnyHashable(ASTContext &ctx, Type type) {
if (auto classDecl = type->getClassOrBoundGenericClass()) {
return classDecl->getName()
== ctx.getSwiftId(KnownFoundationEntity::NSObject) &&
classDecl->getModuleContext()->getName() == ctx.Id_ObjectiveC;
}
if (auto nomDecl = type->getAnyNominal()) {
return nomDecl->getName() == ctx.getIdentifier("AnyHashable") &&
nomDecl->getModuleContext() == ctx.getStdlibModule();
}
return false;
}
static bool isAnyObjectOrAny(Type type) {
return type->isAnyObject() || type->isAny();
}
/// Returns true if \p name matches a keyword in any Clang language mode.
static bool isClangKeyword(Identifier name) {
static const llvm::StringSet<> keywords = []{
llvm::StringSet<> set;
// FIXME: clang::IdentifierInfo /nearly/ has the API we need to do this
// in a more principled way, but not quite.
#define KEYWORD(SPELLING, FLAGS) \
set.insert(#SPELLING);
#define CXX_KEYWORD_OPERATOR(SPELLING, TOK) \
set.insert(#SPELLING);
#include "clang/Basic/TokenKinds.def"
return set;
}();
if (name.empty())
return false;
return keywords.find(name.str()) != keywords.end();
}
namespace {
enum CustomNamesOnly_t : bool {
Normal = false,
CustomNamesOnly = true,
};
/// Whether the type being printed is in function param position.
enum IsFunctionParam_t : bool {
IsFunctionParam = true,
IsNotFunctionParam = false,
};
}
static StringRef getNameForObjC(const ValueDecl *VD,
CustomNamesOnly_t customNamesOnly = Normal) {
assert(isa<ClassDecl>(VD) || isa<ProtocolDecl>(VD) || isa<StructDecl>(VD) ||
isa<EnumDecl>(VD) || isa<EnumElementDecl>(VD));
if (auto objc = VD->getAttrs().getAttribute<ObjCAttr>()) {
if (auto name = objc->getName()) {
assert(name->getNumSelectorPieces() == 1);
return name->getSelectorPieces().front().str();
}
}
if (customNamesOnly)
return StringRef();
if (auto clangDecl = dyn_cast_or_null<clang::NamedDecl>(VD->getClangDecl())) {
if (const clang::IdentifierInfo *II = clangDecl->getIdentifier())
return II->getName();
if (auto *anonDecl = dyn_cast<clang::TagDecl>(clangDecl))
if (auto *anonTypedef = anonDecl->getTypedefNameForAnonDecl())
return anonTypedef->getIdentifier()->getName();
}
return VD->getName().str();
}
/// Returns true if the given selector might be mistaken for an init method
/// by Objective-C ARC.
static bool isMistakableForInit(ObjCSelector selector) {
ArrayRef<Identifier> selectorPieces = selector.getSelectorPieces();
assert(!selectorPieces.empty());
return selectorPieces.front().str().startswith("init");
}
namespace {
using DelayedMemberSet = llvm::SmallSetVector<const ValueDecl *, 32>;
class ObjCPrinter : private DeclVisitor<ObjCPrinter>,
private TypeVisitor<ObjCPrinter, void,
Optional<OptionalTypeKind>>
{
friend ASTVisitor;
friend TypeVisitor;
using NameAndOptional = std::pair<StringRef, bool>;
llvm::DenseMap<std::pair<Identifier, Identifier>, NameAndOptional>
specialNames;
Identifier ID_CFTypeRef;
Module &M;
raw_ostream &os;
SmallVector<const FunctionType *, 4> openFunctionTypes;
const DelayedMemberSet &delayedMembers;
Accessibility minRequiredAccess;
bool protocolMembersOptional = false;
Optional<Type> NSCopyingType;
friend ASTVisitor<ObjCPrinter>;
friend TypeVisitor<ObjCPrinter>;
public:
explicit ObjCPrinter(Module &mod, raw_ostream &out,
DelayedMemberSet &delayed, Accessibility access)
: M(mod), os(out), delayedMembers(delayed), minRequiredAccess(access) {}
void print(const Decl *D) {
PrettyStackTraceDecl trace("printing", D);
ASTVisitor::visit(const_cast<Decl *>(D));
}
void printAdHocCategory(iterator_range<const ValueDecl * const *> members) {
assert(members.begin() != members.end());
const DeclContext *origDC = (*members.begin())->getDeclContext();
auto *baseClass = dyn_cast<ClassDecl>(origDC);
if (!baseClass) {
Type extendedTy = cast<ExtensionDecl>(origDC)->getExtendedType();
baseClass = extendedTy->getClassOrBoundGenericClass();
}
os << "@interface " << getNameForObjC(baseClass)
<< " (SWIFT_EXTENSION(" << origDC->getParentModule()->getName() << "))\n";
printMembers</*allowDelayed*/true>(members);
os << "@end\n\n";
}
bool shouldInclude(const ValueDecl *VD, bool checkParent = true) {
if (!(VD->isObjC() || VD->getAttrs().hasAttribute<CDeclAttr>()))
return false;
if (VD->getFormalAccess() >= minRequiredAccess) {
return true;
} else if (checkParent) {
if (auto ctor = dyn_cast<ConstructorDecl>(VD)) {
// Check if we're overriding an initializer that is visible to obj-c
if (auto parent = ctor->getOverriddenDecl())
return shouldInclude(parent, false);
}
}
return false;
}
private:
/// Prints a protocol adoption list: <code><NSCoding, NSCopying></code>
///
/// This method filters out non-ObjC protocols, along with the special
/// AnyObject protocol.
void printProtocols(ArrayRef<ProtocolDecl *> protos) {
SmallVector<ProtocolDecl *, 4> protosToPrint;
std::copy_if(protos.begin(), protos.end(),
std::back_inserter(protosToPrint),
[this](const ProtocolDecl *PD) -> bool {
if (!shouldInclude(PD))
return false;
auto knownProtocol = PD->getKnownProtocolKind();
if (!knownProtocol)
return true;
return *knownProtocol != KnownProtocolKind::AnyObject;
});
if (protosToPrint.empty())
return;
os << " <";
interleave(protosToPrint,
[this](const ProtocolDecl *PD) { os << getNameForObjC(PD); },
[this] { os << ", "; });
os << ">";
}
/// Prints the members of a class, extension, or protocol.
template <bool AllowDelayed = false, typename R>
void printMembers(R &&members) {
for (const Decl *member : members) {
auto VD = dyn_cast<ValueDecl>(member);
if (!VD || !shouldInclude(VD) || isa<TypeDecl>(VD))
continue;
if (auto FD = dyn_cast<FuncDecl>(VD))
if (FD->isAccessor())
continue;
if (!AllowDelayed && delayedMembers.count(VD)) {
os << "// '" << VD->getFullName() << "' below\n";
continue;
}
if (VD->getAttrs().hasAttribute<OptionalAttr>() != protocolMembersOptional) {
protocolMembersOptional = VD->getAttrs().hasAttribute<OptionalAttr>();
os << (protocolMembersOptional ? "@optional\n" : "@required\n");
}
ASTVisitor::visit(const_cast<ValueDecl*>(VD));
}
}
void printDocumentationComment(Decl *D) {
swift::markup::MarkupContext MC;
auto DC = getSingleDocComment(MC, D);
if (DC.hasValue())
ide::getDocumentationCommentAsDoxygen(DC.getValue(), os);
}
// Ignore other declarations.
void visitDecl(Decl *D) {}
void visitClassDecl(ClassDecl *CD) {
printDocumentationComment(CD);
StringRef customName = getNameForObjC(CD, CustomNamesOnly);
if (customName.empty()) {
llvm::SmallString<32> scratch;
os << "SWIFT_CLASS(\"" << CD->getObjCRuntimeName(scratch) << "\")\n"
<< "@interface " << CD->getName();
} else {
os << "SWIFT_CLASS_NAMED(\"" << CD->getName() << "\")\n"
<< "@interface " << customName;
}
if (Type superTy = CD->getSuperclass())
os << " : " << getNameForObjC(superTy->getClassOrBoundGenericClass());
printProtocols(CD->getLocalProtocols(ConformanceLookupKind::OnlyExplicit));
os << "\n";
printMembers(CD->getMembers());
os << "@end\n";
}
void visitExtensionDecl(ExtensionDecl *ED) {
auto baseClass = ED->getExtendedType()->getClassOrBoundGenericClass();
os << "@interface " << getNameForObjC(baseClass)
<< " (SWIFT_EXTENSION(" << ED->getModuleContext()->getName() << "))";
printProtocols(ED->getLocalProtocols(ConformanceLookupKind::OnlyExplicit));
os << "\n";
printMembers(ED->getMembers());
os << "@end\n";
}
void visitProtocolDecl(ProtocolDecl *PD) {
printDocumentationComment(PD);
StringRef customName = getNameForObjC(PD, CustomNamesOnly);
if (customName.empty()) {
llvm::SmallString<32> scratch;
os << "SWIFT_PROTOCOL(\"" << PD->getObjCRuntimeName(scratch) << "\")\n"
<< "@protocol " << PD->getName();
} else {
os << "SWIFT_PROTOCOL_NAMED(\"" << PD->getName() << "\")\n"
<< "@protocol " << customName;
}
printProtocols(PD->getInheritedProtocols(nullptr));
os << "\n";
assert(!protocolMembersOptional && "protocols start required");
printMembers(PD->getMembers());
protocolMembersOptional = false;
os << "@end\n";
}
void visitEnumDecl(EnumDecl *ED) {
printDocumentationComment(ED);
os << "typedef ";
StringRef customName = getNameForObjC(ED, CustomNamesOnly);
if (customName.empty()) {
os << "SWIFT_ENUM(";
} else {
os << "SWIFT_ENUM_NAMED(";
}
print(ED->getRawType(), OTK_None);
if (customName.empty()) {
os << ", " << ED->getName();
} else {
os << ", " << customName
<< ", \"" << ED->getName() << "\"";
}
os << ") {\n";
for (auto Elt : ED->getAllElements()) {
printDocumentationComment(Elt);
// Print the cases as the concatenation of the enum name with the case
// name.
os << " ";
StringRef customEltName = getNameForObjC(Elt, CustomNamesOnly);
if (customEltName.empty()) {
if (customName.empty()) {
os << ED->getName();
} else {
os << customName;
}
SmallString<16> scratch;
os << camel_case::toSentencecase(Elt->getName().str(), scratch);
} else {
os << customEltName
<< " SWIFT_COMPILE_NAME(\"" << Elt->getName() << "\")";
}
if (auto ILE = cast_or_null<IntegerLiteralExpr>(Elt->getRawValueExpr())) {
os << " = ";
if (ILE->isNegative())
os << "-";
os << ILE->getDigitsText();
}
os << ",\n";
}
os << "};\n";
}
void printSingleMethodParam(StringRef selectorPiece,
const ParamDecl *param,
const clang::ParmVarDecl *clangParam,
bool isNSUIntegerSubscript,
bool isLastPiece) {
os << selectorPiece << ":(";
if ((isNSUIntegerSubscript && isLastPiece) ||
(clangParam && isNSUInteger(clangParam->getType()))) {
os << "NSUInteger";
} else {
print(param->getType(), OTK_None, Identifier(), IsFunctionParam);
}
os << ")";
if (!param->hasName()) {
os << "_";
} else {
Identifier name = param->getName();
os << name;
if (isClangKeyword(name))
os << "_";
}
}
template <typename T>
static const T *findClangBase(const T *member) {
while (member) {
if (member->getClangDecl())
return member;
member = member->getOverriddenDecl();
}
return nullptr;
}
/// Returns true if \p clangTy is the typedef for NSUInteger.
bool isNSUInteger(clang::QualType clangTy) {
const auto *typedefTy = dyn_cast<clang::TypedefType>(clangTy);
if (!typedefTy)
return false;
const clang::IdentifierInfo *nameII = typedefTy->getDecl()->getIdentifier();
if (!nameII)
return false;
if (nameII->getName() != "NSUInteger")
return false;
return true;
}
Type getForeignResultType(AbstractFunctionDecl *AFD,
FunctionType *methodTy,
Optional<ForeignErrorConvention> errorConvention) {
// A foreign error convention can affect the result type as seen in
// Objective-C.
if (errorConvention) {
switch (errorConvention->getKind()) {
case ForeignErrorConvention::ZeroResult:
case ForeignErrorConvention::NonZeroResult:
// The error convention provides the result type.
return errorConvention->getResultType();
case ForeignErrorConvention::NilResult:
// Errors are propagated via 'nil' returns.
return OptionalType::get(methodTy->getResult());
case ForeignErrorConvention::NonNilError:
case ForeignErrorConvention::ZeroPreservedResult:
break;
}
}
return methodTy->getResult();
}
void printAbstractFunctionAsMethod(AbstractFunctionDecl *AFD,
bool isClassMethod,
bool isNSUIntegerSubscript = false) {
printDocumentationComment(AFD);
if (isClassMethod)
os << "+ (";
else
os << "- (";
const clang::ObjCMethodDecl *clangMethod = nullptr;
if (!isNSUIntegerSubscript) {
if (const AbstractFunctionDecl *clangBase = findClangBase(AFD)) {
clangMethod =
dyn_cast_or_null<clang::ObjCMethodDecl>(clangBase->getClangDecl());
}
}
Optional<ForeignErrorConvention> errorConvention
= AFD->getForeignErrorConvention();
Type rawMethodTy = AFD->getInterfaceType()->castTo<AnyFunctionType>()->getResult();
auto methodTy = rawMethodTy->castTo<FunctionType>();
auto resultTy = getForeignResultType(AFD, methodTy, errorConvention);
// Constructors and methods returning DynamicSelf return
// instancetype.
if (isa<ConstructorDecl>(AFD) ||
(isa<FuncDecl>(AFD) && cast<FuncDecl>(AFD)->hasDynamicSelf())) {
if (errorConvention && errorConvention->stripsResultOptionality()) {
printNullability(OTK_Optional, NullabilityPrintKind::ContextSensitive);
} else if (auto ctor = dyn_cast<ConstructorDecl>(AFD)) {
printNullability(ctor->getFailability(),
NullabilityPrintKind::ContextSensitive);
} else {
auto func = cast<FuncDecl>(AFD);
OptionalTypeKind optionalKind;
(void)func->getResultInterfaceType()
->getAnyOptionalObjectType(optionalKind);
printNullability(optionalKind,
NullabilityPrintKind::ContextSensitive);
}
os << "instancetype";
} else if (resultTy->isVoid() &&
AFD->getAttrs().hasAttribute<IBActionAttr>()) {
os << "IBAction";
} else if (clangMethod && isNSUInteger(clangMethod->getReturnType())) {
os << "NSUInteger";
} else {
print(resultTy, OTK_None);
}
os << ")";
auto paramLists = AFD->getParameterLists();
assert(paramLists.size() == 2 && "not an ObjC-compatible method");
ArrayRef<Identifier> selectorPieces
= AFD->getObjCSelector().getSelectorPieces();
const auto ¶ms = paramLists[1]->getArray();
unsigned paramIndex = 0;
for (unsigned i = 0, n = selectorPieces.size(); i != n; ++i) {
if (i > 0) os << ' ';
// Retrieve the selector piece.
StringRef piece = selectorPieces[i].empty() ? StringRef("")
: selectorPieces[i].str();
// If we have an error convention and this is the error
// parameter, print it.
if (errorConvention && i == errorConvention->getErrorParameterIndex()) {
os << piece << ":(";
print(errorConvention->getErrorParameterType(), None);
os << ")error";
continue;
}
// Zero-parameter initializers with a long selector.
if (isa<ConstructorDecl>(AFD) &&
cast<ConstructorDecl>(AFD)->isObjCZeroParameterWithLongSelector()) {
os << piece;
continue;
}
// Zero-parameter methods.
if (params.size() == 0) {
assert(paramIndex == 0);
os << piece;
paramIndex = 1;
continue;
}
const clang::ParmVarDecl *clangParam = nullptr;
if (clangMethod)
clangParam = clangMethod->parameters()[paramIndex];
// Single-parameter methods.
printSingleMethodParam(piece, params[paramIndex], clangParam,
isNSUIntegerSubscript, i == n-1);
++paramIndex;
}
// Swift designated initializers are Objective-C designated initializers.
if (auto ctor = dyn_cast<ConstructorDecl>(AFD)) {
if (ctor->hasStubImplementation()
|| ctor->getFormalAccess() < minRequiredAccess) {
// This will only be reached if the overridden initializer has the
// required access
os << " SWIFT_UNAVAILABLE";
} else if (ctor->isDesignatedInit() &&
!isa<ProtocolDecl>(ctor->getDeclContext())) {
os << " OBJC_DESIGNATED_INITIALIZER";
}
} else {
if (isMistakableForInit(AFD->getObjCSelector())) {
os << " SWIFT_METHOD_FAMILY(none)";
}
if (!methodTy->getResult()->isVoid() &&
!AFD->getAttrs().hasAttribute<DiscardableResultAttr>()) {
os << " SWIFT_WARN_UNUSED_RESULT";
}
}
os << ";\n";
}
void printAbstractFunctionAsFunction(FuncDecl *FD) {
printDocumentationComment(FD);
Optional<ForeignErrorConvention> errorConvention
= FD->getForeignErrorConvention();
assert(!FD->getGenericSignature() &&
"top-level generic functions not supported here");
auto resultTy = getForeignResultType(
FD,
FD->getInterfaceType()->castTo<FunctionType>(),
errorConvention);
// The result type may be a partial function type we need to close
// up later.
PrintMultiPartType multiPart(*this);
visitPart(resultTy, OTK_None);
assert(FD->getAttrs().hasAttribute<CDeclAttr>()
&& "not a cdecl function");
os << ' ' << FD->getAttrs().getAttribute<CDeclAttr>()->Name << '(';
assert(FD->getParameterLists().size() == 1 && "not a C-compatible func");
auto params = FD->getParameterLists().back();
interleave(*params,
[&](const ParamDecl *param) {
print(param->getType(), OTK_None, param->getName(),
IsFunctionParam);
},
[&]{ os << ", "; });
os << ')';
// Finish the result type.
multiPart.finish();
os << ';';
}
void visitFuncDecl(FuncDecl *FD) {
if (FD->getDeclContext()->isTypeContext())
printAbstractFunctionAsMethod(FD, FD->isStatic());
else
printAbstractFunctionAsFunction(FD);
}
void visitConstructorDecl(ConstructorDecl *CD) {
printAbstractFunctionAsMethod(CD, false);
}
bool maybePrintIBOutletCollection(Type ty) {
if (auto unwrapped = ty->getAnyOptionalObjectType())
ty = unwrapped;
auto genericTy = ty->getAs<BoundGenericStructType>();
if (!genericTy || genericTy->getDecl() != M.getASTContext().getArrayDecl())
return false;
assert(genericTy->getGenericArgs().size() == 1);
auto argTy = genericTy->getGenericArgs().front();
if (auto classDecl = argTy->getClassOrBoundGenericClass())
os << "IBOutletCollection(" << getNameForObjC(classDecl) << ") ";
else
os << "IBOutletCollection(id) ";
return true;
}
bool isCFTypeRef(Type ty) {
if (ID_CFTypeRef.empty())
ID_CFTypeRef = M.getASTContext().getIdentifier("CFTypeRef");
const TypeAliasDecl *TAD = nullptr;
while (auto aliasTy = dyn_cast<NameAliasType>(ty.getPointer())) {
TAD = aliasTy->getDecl();
ty = TAD->getUnderlyingType();
}
return TAD && TAD->getName() == ID_CFTypeRef && TAD->hasClangNode();
}
void visitVarDecl(VarDecl *VD) {
assert(VD->getDeclContext()->isTypeContext() &&
"cannot handle global variables right now");
printDocumentationComment(VD);
if (VD->isStatic()) {
// Older Clangs don't support class properties.
os << "SWIFT_CLASS_PROPERTY(";
}
// For now, never promise atomicity.
os << "@property (nonatomic";
if (VD->isStatic())
os << ", class";
ASTContext &ctx = M.getASTContext();
bool isSettable = VD->isSettable(nullptr);
if (isSettable && ctx.LangOpts.EnableAccessControl)
isSettable = (VD->getSetterAccessibility() >= minRequiredAccess);
if (!isSettable)
os << ", readonly";
// Print the ownership semantics, if relevant.
// We treat "unowned" as "assign" (even though it's more like
// "safe_unretained") because we want people to think twice about
// allowing that object to disappear.
Type ty = VD->getType();
if (auto weakTy = ty->getAs<WeakStorageType>()) {
auto innerTy = weakTy->getReferentType()->getAnyOptionalObjectType();
auto innerClass = innerTy->getClassOrBoundGenericClass();
if ((innerClass &&
innerClass->getForeignClassKind()!=ClassDecl::ForeignKind::CFType) ||
(innerTy->isObjCExistentialType() && !isCFTypeRef(innerTy))) {
os << ", weak";
}
} else if (ty->is<UnownedStorageType>()) {
os << ", assign";
} else if (ty->is<UnmanagedStorageType>()) {
os << ", unsafe_unretained";
} else {
Type copyTy = ty;
OptionalTypeKind optionalType;
if (auto unwrappedTy = copyTy->getAnyOptionalObjectType(optionalType))
copyTy = unwrappedTy;
auto nominal = copyTy->getNominalOrBoundGenericNominal();
if (dyn_cast_or_null<StructDecl>(nominal)) {
if (nominal == ctx.getArrayDecl() ||
nominal == ctx.getDictionaryDecl() ||
nominal == ctx.getSetDecl() ||
nominal == ctx.getStringDecl() ||
(!getKnownTypeInfo(nominal) && getObjCBridgedClass(nominal))) {
// We fast-path the most common cases in the condition above.
os << ", copy";
} else if (nominal == ctx.getUnmanagedDecl()) {
os << ", unsafe_unretained";
// Don't print unsafe_unretained twice.
if (auto boundTy = copyTy->getAs<BoundGenericType>()) {
ty = boundTy->getGenericArgs().front();
if (optionalType != OTK_None)
ty = OptionalType::get(optionalType, ty);
}
}
} else if (auto fnTy = copyTy->getAs<FunctionType>()) {
switch (fnTy->getRepresentation()) {
case FunctionTypeRepresentation::Block:
case FunctionTypeRepresentation::Swift:
os << ", copy";
break;
case FunctionTypeRepresentation::Thin:
case FunctionTypeRepresentation::CFunctionPointer:
break;
}
} else if ((dyn_cast_or_null<ClassDecl>(nominal) &&
cast<ClassDecl>(nominal)->getForeignClassKind() !=
ClassDecl::ForeignKind::CFType) ||
(copyTy->isObjCExistentialType() && !isCFTypeRef(copyTy))) {
os << ", strong";
}
}
Identifier objCName = VD->getObjCPropertyName();
bool hasReservedName = isClangKeyword(objCName);
// Handle custom accessor names.
llvm::SmallString<64> buffer;
if (hasReservedName ||
VD->getObjCGetterSelector() !=
VarDecl::getDefaultObjCGetterSelector(ctx, objCName)) {
os << ", getter=" << VD->getObjCGetterSelector().getString(buffer);
}
if (isSettable) {
if (hasReservedName ||
VD->getObjCSetterSelector() !=
VarDecl::getDefaultObjCSetterSelector(ctx, objCName)) {
buffer.clear();
os << ", setter=" << VD->getObjCSetterSelector().getString(buffer);
}
}
os << ") ";
if (VD->getAttrs().hasAttribute<IBOutletAttr>()) {
if (!maybePrintIBOutletCollection(ty))
os << "IBOutlet ";
}
clang::QualType clangTy;
if (const VarDecl *base = findClangBase(VD))
if (auto prop = dyn_cast<clang::ObjCPropertyDecl>(base->getClangDecl()))
clangTy = prop->getType();
if (!clangTy.isNull() && isNSUInteger(clangTy)) {
os << "NSUInteger " << objCName;
if (hasReservedName)
os << "_";
} else {
print(ty, OTK_None, objCName);
}
os << ";";
if (VD->isStatic()) {
os << ")\n";
// Older Clangs don't support class properties, so print the accessors as
// well. This is harmless.
printAbstractFunctionAsMethod(VD->getGetter(), true);
if (isSettable) {
assert(VD->getSetter() && "settable ObjC property missing setter decl");
printAbstractFunctionAsMethod(VD->getSetter(), true);
}
} else {
os << "\n";
if (isMistakableForInit(VD->getObjCGetterSelector()))
printAbstractFunctionAsMethod(VD->getGetter(), false);
if (isSettable && isMistakableForInit(VD->getObjCSetterSelector()))
printAbstractFunctionAsMethod(VD->getSetter(), false);
}
}
void visitSubscriptDecl(SubscriptDecl *SD) {
assert(SD->isInstanceMember() && "static subscripts not supported");
bool isNSUIntegerSubscript = false;
if (auto clangBase = findClangBase(SD)) {
const auto *clangGetter =
cast<clang::ObjCMethodDecl>(clangBase->getClangDecl());
const auto *indexParam = clangGetter->parameters().front();
isNSUIntegerSubscript = isNSUInteger(indexParam->getType());
}
printAbstractFunctionAsMethod(SD->getGetter(), false, isNSUIntegerSubscript);
if (auto setter = SD->getSetter())
printAbstractFunctionAsMethod(setter, false, isNSUIntegerSubscript);
}
/// Visit part of a type, such as the base of a pointer type.
///
/// If a full type is being printed, use print() instead.
void visitPart(Type ty, Optional<OptionalTypeKind> optionalKind) {
TypeVisitor::visit(ty, optionalKind);
}
/// Where nullability information should be printed.
enum class NullabilityPrintKind {
Before,
After,
ContextSensitive,
};
void printNullability(Optional<OptionalTypeKind> kind,
NullabilityPrintKind printKind
= NullabilityPrintKind::After) {
if (!kind)
return;
switch (printKind) {
case NullabilityPrintKind::ContextSensitive:
switch (*kind) {
case OTK_None:
os << "nonnull";
break;
case OTK_Optional:
os << "nullable";
break;
case OTK_ImplicitlyUnwrappedOptional:
os << "null_unspecified";
break;
}
break;
case NullabilityPrintKind::After:
os << ' ';
LLVM_FALLTHROUGH;
case NullabilityPrintKind::Before:
switch (*kind) {
case OTK_None:
os << "_Nonnull";
break;
case OTK_Optional:
os << "_Nullable";
break;
case OTK_ImplicitlyUnwrappedOptional:
os << "_Null_unspecified";
break;
}
break;
}
if (printKind != NullabilityPrintKind::After)
os << ' ';
}
/// Determine whether this generic Swift nominal type maps to a
/// generic Objective-C class.
static bool hasGenericObjCType(const NominalTypeDecl *nominal) {
auto clangDecl = nominal->getClangDecl();
if (!clangDecl) return false;
auto objcClass = dyn_cast<clang::ObjCInterfaceDecl>(clangDecl);
if (!objcClass) return false;
if (objcClass->getTypeParamList() == nullptr) return false;
return true;
}
/// If \p nominal is bridged to an Objective-C class (via a conformance to
/// _ObjectiveCBridgeable), return that class.
///
/// Otherwise returns null.
const ClassDecl *getObjCBridgedClass(const NominalTypeDecl *nominal) {
// Print imported bridgeable decls as their unbridged type.
if (nominal->hasClangNode())
return nullptr;
auto &ctx = nominal->getASTContext();
// Dig out the ObjectiveCBridgeable protocol.
auto proto = ctx.getProtocol(KnownProtocolKind::ObjectiveCBridgeable);
if (!proto) return nullptr;
// Determine whether this nominal type is _ObjectiveCBridgeable.
SmallVector<ProtocolConformance *, 2> conformances;
if (!nominal->lookupConformance(&M, proto, conformances))
return nullptr;
// Dig out the Objective-C type.
auto conformance = conformances.front();
Type objcType = ProtocolConformance::getTypeWitnessByName(
nominal->getDeclaredType(),
ProtocolConformanceRef(conformance),
ctx.Id_ObjectiveCType,
nullptr);
if (!objcType) return nullptr;
// Dig out the Objective-C class.
return objcType->getClassOrBoundGenericClass();
}
/// If the nominal type is bridged to Objective-C (via a conformance
/// to _ObjectiveCBridgeable), print the bridged type.
void printObjCBridgeableType(const NominalTypeDecl *swiftNominal,
const ClassDecl *objcClass,
ArrayRef<Type> typeArgs,
Optional<OptionalTypeKind> optionalKind) {
auto &ctx = swiftNominal->getASTContext();
assert(objcClass);
Type rewrittenArgsBuf[2];
// Detect when the type arguments correspond to the unspecialized
// type, and clear them out. There is some type-specific hackery
// here for:
//
// NSArray<id> --> NSArray
// NSDictionary<NSObject *, id> --> NSDictionary
// NSSet<id> --> NSSet
if (!typeArgs.empty() &&
(!hasGenericObjCType(objcClass)
|| (swiftNominal == ctx.getArrayDecl() &&
isAnyObjectOrAny(typeArgs[0]))
|| (swiftNominal == ctx.getDictionaryDecl() &&
isNSObjectOrAnyHashable(ctx, typeArgs[0]) &&
isAnyObjectOrAny(typeArgs[1]))
|| (swiftNominal == ctx.getSetDecl() &&
isNSObjectOrAnyHashable(ctx, typeArgs[0])))) {
typeArgs = {};
}
// Use the proper upper id<NSCopying> bound for Dictionaries with
// upper-bounded keys.
else if (swiftNominal == ctx.getDictionaryDecl() &&
isNSObjectOrAnyHashable(ctx, typeArgs[0])) {
if (Module *M = ctx.getLoadedModule(ctx.Id_Foundation)) {
if (!NSCopyingType) {
UnqualifiedLookup lookup(ctx.getIdentifier("NSCopying"), M, nullptr);
auto type = lookup.getSingleTypeResult();
if (type && isa<ProtocolDecl>(type)) {
NSCopyingType = type->getDeclaredInterfaceType();
} else {
NSCopyingType = Type();
}
}
if (*NSCopyingType) {
rewrittenArgsBuf[0] = *NSCopyingType;
rewrittenArgsBuf[1] = typeArgs[1];
typeArgs = rewrittenArgsBuf;
}
}
}
// Print the class type.
SmallString<32> objcNameScratch;
os << objcClass->getObjCRuntimeName(objcNameScratch);
// Print the type arguments, if present.
if (!typeArgs.empty()) {
os << "<";
interleave(typeArgs,
[this](Type type) {
printCollectionElement(type);
},
[this] { os << ", "; });
os << ">";
}
os << " *";
printNullability(optionalKind);
}
/// If the nominal type is bridged to Objective-C (via a conformance to
/// _ObjectiveCBridgeable), print the bridged type. Otherwise, nothing is
/// printed.
///
/// \returns true iff printed something.
bool printIfObjCBridgeable(const NominalTypeDecl *nominal,
ArrayRef<Type> typeArgs,
Optional<OptionalTypeKind> optionalKind) {
if (const ClassDecl *objcClass = getObjCBridgedClass(nominal)) {
printObjCBridgeableType(nominal, objcClass, typeArgs, optionalKind);
return true;
}
return false;
}
/// If \p typeDecl is one of the standard library types used to map in Clang
/// primitives and basic types, return the address of the info in
/// \c specialNames containing the Clang name and whether it can be optional.
///
/// Returns null if the name is not one of these known types.
const NameAndOptional *getKnownTypeInfo(const TypeDecl *typeDecl) {
if (specialNames.empty()) {
ASTContext &ctx = M.getASTContext();
#define MAP(SWIFT_NAME, CLANG_REPR, NEEDS_NULLABILITY) \
specialNames[{ctx.StdlibModuleName, ctx.getIdentifier(#SWIFT_NAME)}] = \
{ CLANG_REPR, NEEDS_NULLABILITY}
MAP(CBool, "bool", false);
MAP(CChar, "char", false);
MAP(CWideChar, "wchar_t", false);
MAP(CChar16, "char16_t", false);
MAP(CChar32, "char32_t", false);
MAP(CSignedChar, "signed char", false);