forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPrintAsObjC.cpp
3038 lines (2645 loc) · 102 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 - 2018 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/ASTVisitor.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/AST/SwiftNameTranslation.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 "swift/Parse/Lexer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/Decl.h"
#include "clang/AST/DeclObjC.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Module.h"
#include "clang/Lex/Lexer.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallString.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;
using namespace swift::objc_translation;
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 == ctx.getAnyHashableDecl();
}
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::DenseSet<StringRef> keywords = []{
llvm::DenseSet<StringRef> 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 {
/// Whether the type being printed is in function param position.
enum IsFunctionParam_t : bool {
IsFunctionParam = true,
IsNotFunctionParam = false,
};
} // end anonymous namespace
/// Returns true if the given selector might be classified as an init method
/// by Objective-C ARC.
static bool looksLikeInitMethod(ObjCSelector selector) {
ArrayRef<Identifier> selectorPieces = selector.getSelectorPieces();
assert(!selectorPieces.empty());
auto firstPiece = selectorPieces.front().str();
if (!firstPiece.startswith("init")) return false;
return !(firstPiece.size() > 4 && clang::isLowercase(firstPiece[4]));
}
/// Returns the name of an <os/object.h> type minus the leading "OS_",
/// or an empty string if \p decl is not an <os/object.h> type.
static StringRef maybeGetOSObjectBaseName(const clang::NamedDecl *decl) {
StringRef name = decl->getName();
if (!name.consume_front("OS_"))
return StringRef();
clang::SourceLocation loc = decl->getLocation();
if (!loc.isMacroID())
return StringRef();
// Hack: check to see if the name came from a macro in <os/object.h>.
clang::SourceManager &sourceMgr = decl->getASTContext().getSourceManager();
clang::SourceLocation expansionLoc =
sourceMgr.getImmediateExpansionRange(loc).getBegin();
clang::SourceLocation spellingLoc = sourceMgr.getSpellingLoc(expansionLoc);
if (!sourceMgr.getFilename(spellingLoc).endswith("/os/object.h"))
return StringRef();
return name;
}
/// Returns true if \p decl represents an <os/object.h> type.
static bool isOSObjectType(const clang::Decl *decl) {
auto *named = dyn_cast_or_null<clang::NamedDecl>(decl);
if (!named)
return false;
return !maybeGetOSObjectBaseName(named).empty();
}
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;
ModuleDecl &M;
raw_ostream &os;
SmallVector<const FunctionType *, 4> openFunctionTypes;
const DelayedMemberSet &delayedMembers;
AccessLevel minRequiredAccess;
bool protocolMembersOptional = false;
Optional<Type> NSCopyingType;
friend ASTVisitor<ObjCPrinter>;
friend TypeVisitor<ObjCPrinter>;
public:
explicit ObjCPrinter(ModuleDecl &mod, raw_ostream &out,
DelayedMemberSet &delayed, AccessLevel 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 maybePrintObjCGenericParameters(const ClassDecl *importedClass) {
auto *clangDecl = importedClass->getClangDecl();
auto *objcClass = dyn_cast_or_null<clang::ObjCInterfaceDecl>(clangDecl);
if (!objcClass)
return;
if (!objcClass->getTypeParamList())
return;
assert(objcClass->getTypeParamList()->size() != 0);
os << "<";
interleave(*objcClass->getTypeParamList(),
[this](const clang::ObjCTypeParamDecl *param) {
os << param->getName();
},
[this] { os << ", "; });
os << ">";
}
void printAdHocCategory(iterator_range<const ValueDecl * const *> members) {
assert(members.begin() != members.end());
const DeclContext *origDC = (*members.begin())->getDeclContext();
auto *baseClass = origDC->getSelfClassDecl();
os << "@interface " << getNameForObjC(baseClass);
maybePrintObjCGenericParameters(baseClass);
os << " (SWIFT_EXTENSION(" << origDC->getParentModule()->getName()
<< "))\n";
printMembers</*allowDelayed*/true>(members);
os << "@end\n\n";
}
bool shouldInclude(const ValueDecl *VD) {
return isVisibleToObjC(VD, minRequiredAccess) &&
!VD->getAttrs().hasAttribute<ImplementationOnlyAttr>();
}
private:
/// Prints a protocol adoption list: <code><NSCoding, NSCopying></code>
///
/// This method filters out non-ObjC protocols.
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 {
return shouldInclude(PD);
});
// Drop protocols from the list that are implied by other protocols.
ProtocolType::canonicalizeProtocols(protosToPrint);
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 (isa<AccessorDecl>(VD))
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)
ide::getDocumentationCommentAsDoxygen(DC, os);
}
/// Prints an encoded string, escaped properly for C.
void printEncodedString(StringRef str, bool includeQuotes = true) {
// NB: We don't use raw_ostream::write_escaped() because it does hex escapes
// for non-ASCII chars.
llvm::SmallString<128> Buf;
StringRef decodedStr = Lexer::getEncodedStringSegment(str, Buf);
if (includeQuotes) os << '"';
for (unsigned char c : decodedStr) {
switch (c) {
case '\\':
os << '\\' << '\\';
break;
case '\t':
os << '\\' << 't';
break;
case '\n':
os << '\\' << 'n';
break;
case '"':
os << '\\' << '"';
break;
default:
if (c < 0x20 || c == 0x7F) {
os << '\\' << 'x';
os << llvm::hexdigit((c >> 4) & 0xF);
os << llvm::hexdigit((c >> 0) & 0xF);
} else {
os << c;
}
}
}
if (includeQuotes) os << '"';
}
// For a given Decl and Type, if the type is not an optional return
// the type and OTK_None as the optionality. If the type is
// optional, return the underlying object type, and an optionality
// that is based on the type but overridden by the return value of
// isImplicitlyUnwrappedOptional().
static std::pair<Type, OptionalTypeKind>
getObjectTypeAndOptionality(const ValueDecl *D, Type ty) {
OptionalTypeKind kind;
if (auto objTy =
ty->getReferenceStorageReferent()->getOptionalObjectType()) {
kind = OTK_Optional;
if (D->isImplicitlyUnwrappedOptional())
kind = OTK_ImplicitlyUnwrappedOptional;
return {objTy, kind};
}
return {ty, OTK_None};
}
// Ignore other declarations.
void visitDecl(Decl *D) {}
void visitClassDecl(ClassDecl *CD) {
printDocumentationComment(CD);
// This is just for testing, so we check explicitly for the attribute instead
// of asking if the class is weak imported. If the class has availablility,
// we'll print a SWIFT_AVAIALBLE() which implies __attribute__((weak_imported))
// already.
if (CD->getAttrs().hasAttribute<WeakLinkedAttr>())
os << "SWIFT_WEAK_IMPORT\n";
bool hasResilientAncestry =
CD->checkAncestry().contains(AncestryFlags::ResilientOther);
if (hasResilientAncestry) {
os << "SWIFT_RESILIENT_CLASS";
} else {
os << "SWIFT_CLASS";
}
StringRef customName = getNameForObjC(CD, CustomNamesOnly);
if (customName.empty()) {
llvm::SmallString<32> scratch;
os << "(\"" << CD->getObjCRuntimeName(scratch) << "\")";
printAvailability(CD);
os << "\n@interface " << CD->getName();
} else {
os << "_NAMED(\"" << CD->getName() << "\")";
printAvailability(CD);
os << "\n@interface " << customName;
}
if (auto superDecl = CD->getSuperclassDecl())
os << " : " << getNameForObjC(superDecl);
printProtocols(CD->getLocalProtocols(ConformanceLookupKind::OnlyExplicit));
os << "\n";
printMembers(CD->getMembers());
os << "@end\n";
}
bool isEmptyExtensionDecl(ExtensionDecl *ED) {
auto members = ED->getMembers();
auto hasMembers = std::any_of(members.begin(), members.end(),
[this](const Decl *D) -> bool {
if (auto VD = dyn_cast<ValueDecl>(D))
if (shouldInclude(VD))
return true;
return false;
});
auto protocols = ED->getLocalProtocols(ConformanceLookupKind::OnlyExplicit);
auto hasProtocols = std::any_of(protocols.begin(), protocols.end(),
[this](const ProtocolDecl *PD) -> bool {
return shouldInclude(PD);
});
return (!hasMembers && !hasProtocols);
}
void visitExtensionDecl(ExtensionDecl *ED) {
if (isEmptyExtensionDecl(ED))
return;
auto baseClass = ED->getSelfClassDecl();
if (printAvailability(ED, PrintLeadingSpace::No))
os << "\n";
os << "@interface " << getNameForObjC(baseClass);
maybePrintObjCGenericParameters(baseClass);
os << " (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) << "\")";
printAvailability(PD);
os << "\n@protocol " << PD->getName();
} else {
os << "SWIFT_PROTOCOL_NAMED(\"" << PD->getName() << "\")";
printAvailability(PD);
os << "\n@protocol " << customName;
}
printProtocols(PD->getInheritedProtocols());
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 << ", "
<< (ED->isFormallyExhaustive(/*useDC*/nullptr) ? "closed" : "open")
<< ") {\n";
for (auto Elt : ED->getAllElements()) {
printDocumentationComment(Elt);
// Print the cases as the concatenation of the enum name with the case
// name.
os << " ";
if (printSwiftEnumElemNameInObjC(Elt, os)) {
os << " 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 {
OptionalTypeKind kind;
Type objTy;
std::tie(objTy, kind) =
getObjectTypeAndOptionality(param, param->getInterfaceType());
print(objTy, kind, 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;
}
}
auto result = methodTy->getResult();
if (result->isUninhabited())
return M.getASTContext().TheEmptyTupleType;
return result;
}
/// Returns true if \p sel is the no-argument selector 'init'.
static bool selectorIsInit(ObjCSelector sel) {
return sel.getNumArgs() == 0 &&
sel.getSelectorPieces().front().str() == "init";
}
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->getMethodInterfaceType();
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)->hasDynamicSelfResult())) {
if (errorConvention && errorConvention->stripsResultOptionality()) {
printNullability(OTK_Optional, NullabilityPrintKind::ContextSensitive);
} else if (auto ctor = dyn_cast<ConstructorDecl>(AFD)) {
OptionalTypeKind kind = OTK_None;
if (ctor->isFailable()) {
if (ctor->isImplicitlyUnwrappedOptional())
kind = OTK_ImplicitlyUnwrappedOptional;
else
kind = OTK_Optional;
}
printNullability(kind,
NullabilityPrintKind::ContextSensitive);
} else {
auto func = cast<FuncDecl>(AFD);
OptionalTypeKind kind;
Type objTy;
std::tie(objTy, kind) =
getObjectTypeAndOptionality(func, func->getResultInterfaceType());
printNullability(kind,
NullabilityPrintKind::ContextSensitive);
}
os << "instancetype";
} else if (resultTy->isVoid() &&
AFD->getAttrs().hasAttribute<IBActionAttr>()) {
os << "IBAction";
} else if (clangMethod && isNSUInteger(clangMethod->getReturnType())) {
os << "NSUInteger";
} else {
// IBSegueAction is placed before whatever return value is chosen.
if (AFD->getAttrs().hasAttribute<IBSegueActionAttr>()) {
os << "IBSegueAction ";
}
OptionalTypeKind kind;
Type objTy;
std::tie(objTy, kind) = getObjectTypeAndOptionality(AFD, resultTy);
print(objTy, kind);
}
os << ")";
auto selector = AFD->getObjCSelector();
ArrayRef<Identifier> selectorPieces = selector.getSelectorPieces();
const auto ¶ms = AFD->getParameters()->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.empty()) {
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;
}
bool skipAvailability = false;
bool makeNewUnavailable = false;
bool makeNewExplicitlyAvailable = false;
// 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";
skipAvailability = true;
// If -init is unavailable, then +new should be, too:
makeNewUnavailable = selectorIsInit(selector);
} else {
if (ctor->isDesignatedInit() &&
!isa<ProtocolDecl>(ctor->getDeclContext())) {
os << " OBJC_DESIGNATED_INITIALIZER";
}
// If -init is newly available, +new should be as well if the class
// inherits from NSObject.
if (selectorIsInit(selector) && !ctor->getOverriddenDecl()) {
auto container = ctor->getDeclContext();
auto *classDecl = container->getSelfClassDecl();
if (!classDecl) {
assert(container->getSelfProtocolDecl());
} else {
while (classDecl->hasSuperclass()) {
classDecl = classDecl->getSuperclassDecl();
assert(classDecl &&
"shouldn't PrintAsObjC with invalid superclasses");
}
if (classDecl->hasClangNode() &&
classDecl->getNameStr() == "NSObject") {
makeNewExplicitlyAvailable = true;
}
}
}
}
if (!looksLikeInitMethod(AFD->getObjCSelector())) {
os << " SWIFT_METHOD_FAMILY(init)";
}
} else {
if (looksLikeInitMethod(AFD->getObjCSelector())) {
os << " SWIFT_METHOD_FAMILY(none)";
}
if (methodTy->getResult()->isUninhabited()) {
os << " SWIFT_NORETURN";
} else if (!methodTy->getResult()->isVoid() &&
!AFD->getAttrs().hasAttribute<DiscardableResultAttr>()) {
os << " SWIFT_WARN_UNUSED_RESULT";
}
}
if (!skipAvailability) {
printAvailability(AFD);
}
if (auto accessor = dyn_cast<AccessorDecl>(AFD)) {
printSwift3ObjCDeprecatedInference(accessor->getStorage());
} else {
printSwift3ObjCDeprecatedInference(AFD);
}
os << ";\n";
if (makeNewUnavailable) {
assert(!makeNewExplicitlyAvailable);
// Downgrade this to a warning in pre-Swift-5 mode. This isn't perfect
// because it's a diagnostic inflicted on /clients/, but it's close
// enough. It really is invalid to call +new when -init is unavailable.
StringRef annotationName = "SWIFT_UNAVAILABLE_MSG";
if (!M.getASTContext().isSwiftVersionAtLeast(5))
annotationName = "SWIFT_DEPRECATED_MSG";
os << "+ (nonnull instancetype)new " << annotationName
<< "(\"-init is unavailable\");\n";
} else if (makeNewExplicitlyAvailable) {
os << "+ (nonnull instancetype)new;\n";
}
}
void printAbstractFunctionAsFunction(FuncDecl *FD) {
printDocumentationComment(FD);
Optional<ForeignErrorConvention> errorConvention
= FD->getForeignErrorConvention();
assert(!FD->getGenericSignature() &&
"top-level generic functions not supported here");
auto funcTy = FD->getInterfaceType()->castTo<FunctionType>();
auto resultTy = getForeignResultType(FD, funcTy, errorConvention);
// The result type may be a partial function type we need to close
// up later.
PrintMultiPartType multiPart(*this);
OptionalTypeKind kind;
Type objTy;
std::tie(objTy, kind) = getObjectTypeAndOptionality(FD, resultTy);
visitPart(objTy, kind);
assert(FD->getAttrs().hasAttribute<CDeclAttr>()
&& "not a cdecl function");
os << ' ' << FD->getAttrs().getAttribute<CDeclAttr>()->Name << '(';
auto params = FD->getParameters();
if (params->size()) {
interleave(*params,
[&](const ParamDecl *param) {
OptionalTypeKind kind;
Type objTy;
std::tie(objTy, kind) = getObjectTypeAndOptionality(
param, param->getInterfaceType());
print(objTy, kind, param->getName(), IsFunctionParam);
},
[&] { os << ", "; });
} else {
os << "void";
}
os << ')';
// Finish the result type.
multiPart.finish();
if (funcTy->getResult()->isUninhabited()) {
os << " SWIFT_NORETURN";
} else if (!funcTy->getResult()->isVoid() &&
!FD->getAttrs().hasAttribute<DiscardableResultAttr>()) {
os << " SWIFT_WARN_UNUSED_RESULT";
}
printAvailability(FD);
os << ';';
}
enum class PrintLeadingSpace : bool {
No = false,
Yes = true
};
/// Returns \c true if anything was printed.
bool printAvailability(const Decl *D, PrintLeadingSpace printLeadingSpace =
PrintLeadingSpace::Yes) {
bool hasPrintedAnything = false;
auto maybePrintLeadingSpace = [&] {
if (printLeadingSpace == PrintLeadingSpace::Yes || hasPrintedAnything)
os << " ";
hasPrintedAnything = true;
};
for (auto AvAttr : D->getAttrs().getAttributes<AvailableAttr>()) {
if (AvAttr->Platform == PlatformKind::none) {
if (AvAttr->PlatformAgnostic ==
PlatformAgnosticAvailabilityKind::Unavailable) {
// Availability for *
if (!AvAttr->Rename.empty() && isa<ValueDecl>(D)) {
// rename
maybePrintLeadingSpace();
os << "SWIFT_UNAVAILABLE_MSG(\"'"
<< cast<ValueDecl>(D)->getBaseName()
<< "' has been renamed to '";
printRenameForDecl(AvAttr, cast<ValueDecl>(D), false);
os << '\'';
if (!AvAttr->Message.empty()) {
os << ": ";
printEncodedString(AvAttr->Message, false);
}
os << "\")";
} else if (!AvAttr->Message.empty()) {
maybePrintLeadingSpace();
os << "SWIFT_UNAVAILABLE_MSG(";
printEncodedString(AvAttr->Message);
os << ")";
} else {
maybePrintLeadingSpace();
os << "SWIFT_UNAVAILABLE";
}
break;
}
if (AvAttr->isUnconditionallyDeprecated()) {
if (!AvAttr->Rename.empty() || !AvAttr->Message.empty()) {
maybePrintLeadingSpace();
os << "SWIFT_DEPRECATED_MSG(";
printEncodedString(AvAttr->Message);
if (!AvAttr->Rename.empty()) {
os << ", ";
printRenameForDecl(AvAttr, cast<ValueDecl>(D), true);
}
os << ")";
} else {
maybePrintLeadingSpace();
os << "SWIFT_DEPRECATED";
}
}
continue;
}
// Availability for a specific platform
if (!AvAttr->Introduced.hasValue() && !AvAttr->Deprecated.hasValue() &&
!AvAttr->Obsoleted.hasValue() &&
!AvAttr->isUnconditionallyDeprecated() &&
!AvAttr->isUnconditionallyUnavailable()) {
continue;
}
const char *plat;
switch (AvAttr->Platform) {
case PlatformKind::OSX:
plat = "macos";
break;
case PlatformKind::iOS:
plat = "ios";
break;
case PlatformKind::tvOS:
plat = "tvos";
break;
case PlatformKind::watchOS:
plat = "watchos";
break;
case PlatformKind::OSXApplicationExtension:
plat = "macos_app_extension";
break;
case PlatformKind::iOSApplicationExtension:
plat = "ios_app_extension";
break;
case PlatformKind::tvOSApplicationExtension:
plat = "tvos_app_extension";
break;
case PlatformKind::watchOSApplicationExtension:
plat = "watchos_app_extension";
break;
case PlatformKind::none:
llvm_unreachable("handled above");
}
maybePrintLeadingSpace();
os << "SWIFT_AVAILABILITY(" << plat;
if (AvAttr->isUnconditionallyUnavailable()) {
os << ",unavailable";
} else {
if (AvAttr->Introduced.hasValue()) {
os << ",introduced=" << AvAttr->Introduced.getValue().getAsString();
}
if (AvAttr->Deprecated.hasValue()) {
os << ",deprecated=" << AvAttr->Deprecated.getValue().getAsString();
} else if (AvAttr->isUnconditionallyDeprecated()) {
// We need to specify some version, we can't just say deprecated.
// We also can't deprecate it before it's introduced.
if (AvAttr->Introduced.hasValue()) {
os << ",deprecated=" << AvAttr->Introduced.getValue().getAsString();
} else {
os << ",deprecated=0.0.1";
}
}
if (AvAttr->Obsoleted.hasValue()) {
os << ",obsoleted=" << AvAttr->Obsoleted.getValue().getAsString();
}
}
if (!AvAttr->Rename.empty() && isa<ValueDecl>(D)) {
os << ",message=\"'" << cast<ValueDecl>(D)->getBaseName()
<< "' has been renamed to '";
printRenameForDecl(AvAttr, cast<ValueDecl>(D), false);
os << '\'';
if (!AvAttr->Message.empty()) {
os << ": ";
printEncodedString(AvAttr->Message, false);
}
os << "\"";
} else if (!AvAttr->Message.empty()) {
os << ",message=";
printEncodedString(AvAttr->Message);
}
os << ")";
}
return hasPrintedAnything;
}
const ValueDecl *getRenameDecl(const ValueDecl *D,
const ParsedDeclName renamedParsedDeclName) {
auto declContext = D->getDeclContext();
ASTContext &astContext = D->getASTContext();
auto renamedDeclName = renamedParsedDeclName.formDeclName(astContext);
if (isa<ClassDecl>(D) || isa<ProtocolDecl>(D)) {
if (!renamedParsedDeclName.ContextName.empty()) {
return nullptr;
}
UnqualifiedLookup lookup(renamedDeclName.getBaseIdentifier(),
declContext->getModuleScopeContext(), nullptr,
SourceLoc(),
UnqualifiedLookup::Flags::TypeLookup);
return lookup.getSingleTypeResult();
}
TypeDecl *typeDecl = declContext->getSelfNominalTypeDecl();
const ValueDecl *renamedDecl = nullptr;
SmallVector<ValueDecl *, 4> lookupResults;
declContext->lookupQualified(typeDecl->getDeclaredInterfaceType(),
renamedDeclName, NL_QualifiedDefault, nullptr,
lookupResults);
if (lookupResults.size() == 1) {
auto candidate = lookupResults[0];
if (!shouldInclude(candidate))
return nullptr;
if (candidate->getKind() != D->getKind() ||
(candidate->isInstanceMember() !=
cast<ValueDecl>(D)->isInstanceMember()))
return nullptr;
renamedDecl = candidate;
} else {
for (auto candidate : lookupResults) {
if (!shouldInclude(candidate))
continue;
if (candidate->getKind() != D->getKind() ||
(candidate->isInstanceMember() !=
cast<ValueDecl>(D)->isInstanceMember()))
continue;
if (isa<AbstractFunctionDecl>(candidate)) {
auto cParams = cast<AbstractFunctionDecl>(candidate)->getParameters();
auto dParams = cast<AbstractFunctionDecl>(D)->getParameters();
if (cParams->size() != dParams->size())
continue;
bool hasSameParameterTypes = true;
for (auto index : indices(*cParams)) {
auto cParamsType = cParams->get(index)->getType();
auto dParamsType = dParams->get(index)->getType();
if (!cParamsType->matchesParameter(dParamsType,
TypeMatchOptions())) {