-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathImportDecl.cpp
9597 lines (8282 loc) · 372 KB
/
ImportDecl.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
//===--- ImportDecl.cpp - Import Clang Declarations -----------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// This file implements support for importing Clang declarations into Swift.
//
//===----------------------------------------------------------------------===//
#include "CFTypeInfo.h"
#include "ImporterImpl.h"
#include "ClangDerivedConformances.h"
#include "SwiftDeclSynthesizer.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/Attr.h"
#include "swift/AST/Builtins.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/Decl.h"
#include "swift/AST/DiagnosticsClangImporter.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/NameLookupRequests.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/Types.h"
#include "swift/Basic/Defer.h"
#include "swift/Basic/PrettyStackTrace.h"
#include "swift/Basic/Statistic.h"
#include "swift/Basic/StringExtras.h"
#include "swift/Basic/Version.h"
#include "swift/ClangImporter/CXXMethodBridging.h"
#include "swift/ClangImporter/ClangImporterRequests.h"
#include "swift/ClangImporter/ClangModule.h"
#include "swift/Parse/Lexer.h"
#include "swift/Parse/Parser.h"
#include "swift/Strings.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/Attr.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjCCommon.h"
#include "clang/Basic/CharInfo.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/Lookup.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/Path.h"
#include <algorithm>
#define DEBUG_TYPE "Clang module importer"
STATISTIC(NumTotalImportedEntities, "# of imported clang entities");
STATISTIC(NumFactoryMethodsAsInitializers,
"# of factory methods mapped to initializers");
using namespace swift;
using namespace importer;
namespace swift {
namespace inferred_attributes {
enum {
requires_stored_property_inits = 0x01
};
} // end namespace inferred_attributes
} // end namespace swift
namespace {
struct AccessorInfo {
AbstractStorageDecl *Storage;
AccessorKind Kind;
};
} // end anonymous namespace
static bool isInSystemModule(const DeclContext *D) {
return cast<ClangModuleUnit>(D->getModuleScopeContext())->isSystemModule();
}
static FuncDecl *
createFuncOrAccessor(ClangImporter::Implementation &impl, SourceLoc funcLoc,
std::optional<AccessorInfo> accessorInfo, DeclName name,
SourceLoc nameLoc, GenericParamList *genericParams,
ParameterList *bodyParams, Type resultTy, bool async,
bool throws, DeclContext *dc, ClangNode clangNode) {
FuncDecl *decl;
if (accessorInfo) {
decl = AccessorDecl::create(
impl.SwiftContext, funcLoc,
/*accessorKeywordLoc*/ SourceLoc(), accessorInfo->Kind,
accessorInfo->Storage, async, /*AsyncLoc=*/SourceLoc(),
throws, /*ThrowsLoc=*/SourceLoc(), /*ThrownType=*/TypeLoc(),
bodyParams, resultTy, dc, clangNode);
} else {
decl = FuncDecl::createImported(impl.SwiftContext, funcLoc, name, nameLoc,
async, throws, /*thrownType=*/Type(),
bodyParams, resultTy,
genericParams, dc, clangNode);
}
impl.importSwiftAttrAttributes(decl);
return decl;
}
void ClangImporter::Implementation::makeComputed(AbstractStorageDecl *storage,
AccessorDecl *getter,
AccessorDecl *setter) {
assert(getter);
// The synthesized computed property can either use a `get` or an
// `unsafeAddress` accessor.
auto isAddress = getter->getAccessorKind() == AccessorKind::Address;
storage->getASTContext().evaluator.cacheOutput(HasStorageRequest{storage}, false);
if (setter) {
if (isAddress)
assert(setter->getAccessorKind() == AccessorKind::MutableAddress);
storage->setImplInfo(
isAddress ? StorageImplInfo(ReadImplKind::Address,
WriteImplKind::MutableAddress,
ReadWriteImplKind::MutableAddress)
: StorageImplInfo::getMutableComputed());
storage->setAccessors(SourceLoc(), {getter, setter}, SourceLoc());
} else {
storage->setImplInfo(isAddress ? StorageImplInfo(ReadImplKind::Address)
: StorageImplInfo::getImmutableComputed());
storage->setAccessors(SourceLoc(), {getter}, SourceLoc());
}
}
bool ClangImporter::Implementation::recordHasReferenceSemantics(
const clang::RecordDecl *decl, ASTContext &ctx) {
if (!isa<clang::CXXRecordDecl>(decl) && !ctx.LangOpts.CForeignReferenceTypes)
return false;
return decl->hasAttrs() && llvm::any_of(decl->getAttrs(), [](auto *attr) {
if (auto swiftAttr = dyn_cast<clang::SwiftAttrAttr>(attr))
return swiftAttr->getAttribute() == "import_reference" ||
// TODO: Remove this once libSwift hosttools no longer
// requires it.
swiftAttr->getAttribute() == "import_as_ref";
return false;
});
}
#ifndef NDEBUG
static bool verifyNameMapping(MappedTypeNameKind NameMapping,
StringRef left, StringRef right) {
return NameMapping == MappedTypeNameKind::DoNothing || left != right;
}
#endif
/// Map a well-known C type to a swift type from the standard library.
///
/// \param IsError set to true when we know the corresponding swift type name,
/// but we could not find it. (For example, the type was not defined in the
/// standard library or the required standard library module was not imported.)
/// This should be a hard error, we don't want to map the type only sometimes.
///
/// \returns A pair of a swift type and its name that corresponds to a given
/// C type.
static std::pair<Type, StringRef>
getSwiftStdlibType(const clang::TypedefNameDecl *D,
Identifier Name,
ClangImporter::Implementation &Impl,
bool *IsError, MappedTypeNameKind &NameMapping) {
*IsError = false;
MappedCTypeKind CTypeKind;
unsigned Bitwidth;
StringRef SwiftModuleName;
bool IsSwiftModule; // True if SwiftModuleName == STDLIB_NAME.
StringRef SwiftTypeName;
bool CanBeMissing;
do {
#define MAP_TYPE(C_TYPE_NAME, C_TYPE_KIND, C_TYPE_BITWIDTH, \
SWIFT_MODULE_NAME, SWIFT_TYPE_NAME, \
CAN_BE_MISSING, C_NAME_MAPPING) \
if (Name.str() == C_TYPE_NAME) { \
CTypeKind = MappedCTypeKind::C_TYPE_KIND; \
Bitwidth = C_TYPE_BITWIDTH; \
SwiftModuleName = SWIFT_MODULE_NAME; \
IsSwiftModule = SwiftModuleName == STDLIB_NAME; \
SwiftTypeName = SWIFT_TYPE_NAME; \
CanBeMissing = CAN_BE_MISSING; \
NameMapping = MappedTypeNameKind::C_NAME_MAPPING; \
assert(verifyNameMapping(MappedTypeNameKind::C_NAME_MAPPING, \
C_TYPE_NAME, SWIFT_TYPE_NAME) && \
"MappedTypes.def: Identical names must use DoNothing"); \
break; \
}
#include "MappedTypes.def"
// We handle `BOOL` as a special case because the selection here is more
// complicated as the type alias exists on multiple platforms as different
// types. It appears in an Objective-C context where it is a `signed char`
// and appears in Windows as an `int`. Furthermore, you can actually have
// the two interoperate, which requires a further bit of logic to
// disambiguate the type aliasing behaviour. To complicate things, the two
// aliases bridge to different types - `ObjCBool` for Objective-C and
// `WindowsBool` for Windows's `BOOL` type.
if (Name.str() == "BOOL") {
auto &CASTContext = Impl.getClangASTContext();
auto &SwiftASTContext = Impl.SwiftContext;
// Default to Objective-C `BOOL`
CTypeKind = MappedCTypeKind::ObjCBool;
if (CASTContext.getTargetInfo().getTriple().isOSWindows()) {
// On Windows fall back to Windows `BOOL`
CTypeKind = MappedCTypeKind::SignedInt;
// If Objective-C interop is enabled, and we match the Objective-C
// `BOOL` type, then switch back to `ObjCBool`.
if (SwiftASTContext.LangOpts.EnableObjCInterop &&
CASTContext.hasSameType(D->getUnderlyingType(),
CASTContext.ObjCBuiltinBoolTy))
CTypeKind = MappedCTypeKind::ObjCBool;
}
if (CTypeKind == MappedCTypeKind::ObjCBool) {
Bitwidth = 8;
SwiftModuleName = StringRef("ObjectiveC");
IsSwiftModule = false;
SwiftTypeName = "ObjCBool";
NameMapping = MappedTypeNameKind::DoNothing;
CanBeMissing = false;
assert(verifyNameMapping(MappedTypeNameKind::DoNothing,
"BOOL", "ObjCBool") &&
"MappedTypes.def: Identical names must use DoNothing");
} else {
assert(CTypeKind == MappedCTypeKind::SignedInt &&
"expected Windows `BOOL` desugared to `int`");
Bitwidth = 32;
SwiftModuleName = StringRef("WinSDK");
IsSwiftModule = false;
SwiftTypeName = "WindowsBool";
NameMapping = MappedTypeNameKind::DoNothing;
CanBeMissing = true;
assert(verifyNameMapping(MappedTypeNameKind::DoNothing,
"BOOL", "WindowsBool") &&
"MappedTypes.def: Identical names must use DoNothing");
}
break;
}
// We did not find this type, thus it is not mapped.
return std::make_pair(Type(), "");
} while (0);
clang::ASTContext &ClangCtx = Impl.getClangASTContext();
auto ClangType = D->getUnderlyingType();
// If the C type does not have the expected size, don't import it as a stdlib
// type.
unsigned ClangTypeSize = ClangCtx.getTypeSize(ClangType);
if (Bitwidth != 0 && Bitwidth != ClangTypeSize)
return std::make_pair(Type(), "");
// Check other expected properties of the C type.
switch(CTypeKind) {
case MappedCTypeKind::UnsignedInt:
if (!ClangType->isUnsignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::SignedInt:
if (!ClangType->isSignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::UnsignedWord:
if (ClangTypeSize != 64 && ClangTypeSize != 32)
return std::make_pair(Type(), "");
if (!ClangType->isUnsignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::SignedWord:
if (ClangTypeSize != 64 && ClangTypeSize != 32)
return std::make_pair(Type(), "");
if (!ClangType->isSignedIntegerType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::FloatIEEEsingle:
case MappedCTypeKind::FloatIEEEdouble:
case MappedCTypeKind::FloatX87DoubleExtended: {
if (!ClangType->isFloatingType())
return std::make_pair(Type(), "");
const llvm::fltSemantics &Sem = ClangCtx.getFloatTypeSemantics(ClangType);
switch(CTypeKind) {
case MappedCTypeKind::FloatIEEEsingle:
assert(Bitwidth == 32 && "FloatIEEEsingle should be 32 bits wide");
if (&Sem != &APFloat::IEEEsingle())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::FloatIEEEdouble:
assert(Bitwidth == 64 && "FloatIEEEdouble should be 64 bits wide");
if (&Sem != &APFloat::IEEEdouble())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::FloatX87DoubleExtended:
assert(Bitwidth == 80 && "FloatX87DoubleExtended should be 80 bits wide");
if (&Sem != &APFloat::x87DoubleExtended())
return std::make_pair(Type(), "");
break;
default:
llvm_unreachable("should see only floating point types here");
}
}
break;
case MappedCTypeKind::VaList:
switch (ClangCtx.getTargetInfo().getBuiltinVaListKind()) {
case clang::TargetInfo::CharPtrBuiltinVaList:
case clang::TargetInfo::VoidPtrBuiltinVaList:
case clang::TargetInfo::PowerABIBuiltinVaList:
case clang::TargetInfo::AAPCSABIBuiltinVaList:
case clang::TargetInfo::HexagonBuiltinVaList:
assert(ClangCtx.getTypeSize(ClangCtx.VoidPtrTy) == ClangTypeSize &&
"expected va_list type to be sizeof(void *)");
break;
case clang::TargetInfo::AArch64ABIBuiltinVaList:
break;
case clang::TargetInfo::PNaClABIBuiltinVaList:
case clang::TargetInfo::SystemZBuiltinVaList:
case clang::TargetInfo::X86_64ABIBuiltinVaList:
return std::make_pair(Type(), "");
}
break;
case MappedCTypeKind::ObjCBool:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.ObjCBuiltinBoolTy) &&
!(ClangCtx.getBOOLDecl() &&
ClangCtx.hasSameType(ClangType, ClangCtx.getBOOLType())))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCSel:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.getObjCSelType()) &&
!ClangCtx.hasSameType(ClangType,
ClangCtx.getObjCSelRedefinitionType()))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCId:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.getObjCIdType()) &&
!ClangCtx.hasSameType(ClangType,
ClangCtx.getObjCIdRedefinitionType()))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::ObjCClass:
if (!ClangCtx.hasSameType(ClangType, ClangCtx.getObjCClassType()) &&
!ClangCtx.hasSameType(ClangType,
ClangCtx.getObjCClassRedefinitionType()))
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::CGFloat:
if (!ClangType->isFloatingType())
return std::make_pair(Type(), "");
break;
case MappedCTypeKind::Block:
if (!ClangType->isBlockPointerType())
return std::make_pair(Type(), "");
break;
}
ModuleDecl *M;
if (IsSwiftModule)
M = Impl.getStdlibModule();
else
M = Impl.getNamedModule(SwiftModuleName);
if (!M) {
// User did not import the library module that contains the type we want to
// substitute.
*IsError = true;
return std::make_pair(Type(), "");
}
Type SwiftType = Impl.getNamedSwiftType(M, SwiftTypeName);
if (!SwiftType && CTypeKind == MappedCTypeKind::CGFloat) {
// Look for CGFloat in CoreFoundation.
M = Impl.getNamedModule("CoreFoundation");
SwiftType = Impl.getNamedSwiftType(M, SwiftTypeName);
}
if (!SwiftType && !CanBeMissing) {
// The required type is not defined in the standard library.
// The required type is not defined in the library, or the user has not
// imported the library that defines it (so `M` was null and
// `getNamedSwiftType()` returned early).
*IsError = true;
return std::make_pair(Type(), "");
}
return std::make_pair(SwiftType, SwiftTypeName);
}
static bool isNSDictionaryMethod(const clang::ObjCMethodDecl *MD,
clang::Selector cmd) {
if (MD->getSelector() != cmd)
return false;
if (isa<clang::ObjCProtocolDecl>(MD->getDeclContext()))
return false;
if (MD->getClassInterface()->getName() != "NSDictionary")
return false;
return true;
}
void ClangImporter::Implementation::addSynthesizedTypealias(
NominalTypeDecl *nominal, Identifier name, Type underlyingType) {
auto &ctx = nominal->getASTContext();
auto typealias = new (ctx) TypeAliasDecl(SourceLoc(), SourceLoc(), name,
SourceLoc(), nullptr, nominal);
typealias->setUnderlyingType(underlyingType);
typealias->setAccess(AccessLevel::Public);
typealias->setImplicit();
nominal->addMember(typealias);
}
void ClangImporter::Implementation::addSynthesizedProtocolAttrs(
NominalTypeDecl *nominal,
ArrayRef<KnownProtocolKind> synthesizedProtocolAttrs, bool isUnchecked) {
auto &ctx = nominal->getASTContext();
for (auto kind : synthesizedProtocolAttrs) {
// This is unfortunately not an error because some test use mock protocols.
// If those tests were updated, we could assert that
// ctx.getProtocol(kind) != nulltpr which would be nice.
if (auto proto = ctx.getProtocol(kind))
nominal->getAttrs().add(
new (ctx) SynthesizedProtocolAttr(ctx.getProtocol(kind), this,
isUnchecked));
}
}
/// Retrieve the element interface type and key param decl of a subscript
/// setter.
static std::pair<Type, ParamDecl *> decomposeSubscriptSetter(FuncDecl *setter) {
auto *PL = setter->getParameters();
if (PL->size() != 2)
return {nullptr, nullptr};
// Setter type is (self) -> (elem_type, key_type) -> ()
Type elementType = setter->getInterfaceType()
->castTo<AnyFunctionType>()
->getResult()
->castTo<AnyFunctionType>()
->getParams().front().getParameterType();
ParamDecl *keyDecl = PL->get(1);
return {elementType, keyDecl};
}
/// Rectify the (possibly different) types determined by the
/// getter and setter for a subscript.
///
/// \param canUpdateType whether the type of subscript can be
/// changed from the getter type to something compatible with both
/// the getter and the setter.
///
/// \returns the type to be used for the subscript, or a null type
/// if the types cannot be rectified.
static ImportedType rectifySubscriptTypes(Type getterType, bool getterIsIUO,
Type setterType, bool canUpdateType) {
// If the caller couldn't provide a setter type, there is
// nothing to rectify.
if (!setterType)
return {nullptr, false};
// Trivial case: same type in both cases.
if (getterType->isEqual(setterType))
return {getterType, getterIsIUO};
// The getter/setter types are different. If we cannot update
// the type, we have to fail.
if (!canUpdateType)
return {nullptr, false};
// Unwrap one level of optionality from each.
if (Type getterObjectType = getterType->getOptionalObjectType())
getterType = getterObjectType;
if (Type setterObjectType = setterType->getOptionalObjectType())
setterType = setterObjectType;
// If they are still different, fail.
// FIXME: We could produce the greatest common supertype of the
// two types.
if (!getterType->isEqual(setterType))
return {nullptr, false};
// Create an optional of the object type that can be implicitly
// unwrapped which subsumes both behaviors.
return {OptionalType::get(setterType), true};
}
/// Add an AvailableAttr to the declaration for the given
/// version range.
static void applyAvailableAttribute(Decl *decl, AvailabilityContext &info,
ASTContext &C) {
// If the range is "all", this is the same as not having an available
// attribute.
if (info.isAlwaysAvailable())
return;
llvm::VersionTuple noVersion;
auto AvAttr = new (C) AvailableAttr(SourceLoc(), SourceRange(),
targetPlatform(C.LangOpts),
/*Message=*/StringRef(),
/*Rename=*/StringRef(),
/*RenameDecl=*/nullptr,
info.getOSVersion().getLowerEndpoint(),
/*IntroducedRange*/SourceRange(),
/*Deprecated=*/noVersion,
/*DeprecatedRange*/SourceRange(),
/*Obsoleted=*/noVersion,
/*ObsoletedRange*/SourceRange(),
PlatformAgnosticAvailabilityKind::None,
/*Implicit=*/false,
/*SPI*/false);
decl->getAttrs().add(AvAttr);
}
/// Synthesize availability attributes for protocol requirements
/// based on availability of the types mentioned in the requirements.
static void inferProtocolMemberAvailability(ClangImporter::Implementation &impl,
DeclContext *dc, Decl *member) {
// Don't synthesize attributes if there is already an
// availability annotation.
if (member->getAttrs().hasAttribute<AvailableAttr>())
return;
auto *valueDecl = dyn_cast<ValueDecl>(member);
if (!valueDecl)
return;
AvailabilityContext requiredRange =
AvailabilityInference::inferForType(valueDecl->getInterfaceType());
ASTContext &C = impl.SwiftContext;
const Decl *innermostDecl = dc->getInnermostDeclarationDeclContext();
AvailabilityContext containingDeclRange =
AvailabilityInference::availableRange(innermostDecl, C);
requiredRange.intersectWith(containingDeclRange);
applyAvailableAttribute(valueDecl, requiredRange, C);
}
/// Synthesizer callback for the error domain property getter.
static std::pair<BraceStmt *, bool>
synthesizeErrorDomainGetterBody(AbstractFunctionDecl *afd, void *context) {
auto getterDecl = cast<AccessorDecl>(afd);
ASTContext &ctx = getterDecl->getASTContext();
auto contextData =
llvm::PointerIntPair<ValueDecl *, 1, bool>::getFromOpaqueValue(context);
auto swiftValueDecl = contextData.getPointer();
bool isImplicit = contextData.getInt();
DeclRefExpr *domainDeclRef = new (ctx)
DeclRefExpr(ConcreteDeclRef(swiftValueDecl), {}, isImplicit);
domainDeclRef->setType(
getterDecl->mapTypeIntoContext(swiftValueDecl->getInterfaceType()));
auto *ret = ReturnStmt::createImplicit(ctx, domainDeclRef);
return { BraceStmt::create(ctx, SourceLoc(), {ret}, SourceLoc(), isImplicit),
/*isTypeChecked=*/true };
}
/// Add a domain error member, as required by conformance to
/// _BridgedStoredNSError.
/// \returns true on success, false on failure
static bool addErrorDomain(NominalTypeDecl *swiftDecl,
clang::NamedDecl *errorDomainDecl,
ClangImporter::Implementation &importer) {
auto &C = importer.SwiftContext;
auto swiftValueDecl = dyn_cast_or_null<ValueDecl>(
importer.importDecl(errorDomainDecl, importer.CurrentVersion));
auto stringTy = C.getStringType();
assert(stringTy && "no string type available");
if (!swiftValueDecl || !swiftValueDecl->getInterfaceType()->isString()) {
// Couldn't actually import it as an error enum, fall back to enum
return false;
}
bool isStatic = true;
bool isImplicit = true;
// Make the property decl
auto errorDomainPropertyDecl = new (C) VarDecl(
/*IsStatic*/isStatic, VarDecl::Introducer::Var,
SourceLoc(), C.Id_errorDomain, swiftDecl);
errorDomainPropertyDecl->setInterfaceType(stringTy);
errorDomainPropertyDecl->setAccess(AccessLevel::Public);
auto *params = ParameterList::createEmpty(C);
auto getterDecl = AccessorDecl::create(
C,
/*FuncLoc=*/SourceLoc(),
/*AccessorKeywordLoc=*/SourceLoc(), AccessorKind::Get,
errorDomainPropertyDecl,
/*Async=*/false, /*AsyncLoc=*/SourceLoc(),
/*Throws=*/false, /*ThrowsLoc=*/SourceLoc(),
/*ThrownType=*/TypeLoc(), params, stringTy, swiftDecl);
getterDecl->setIsObjC(false);
getterDecl->setIsDynamic(false);
getterDecl->setIsTransparent(false);
swiftDecl->addMember(errorDomainPropertyDecl);
importer.makeComputed(errorDomainPropertyDecl, getterDecl, nullptr);
getterDecl->setImplicit();
getterDecl->setAccess(AccessLevel::Public);
llvm::PointerIntPair<ValueDecl *, 1, bool> contextData(swiftValueDecl,
isImplicit);
getterDecl->setBodySynthesizer(synthesizeErrorDomainGetterBody,
contextData.getOpaqueValue());
return true;
}
/// As addErrorDomain above, but performs a lookup
static bool addErrorDomain(NominalTypeDecl *swiftDecl,
StringRef errorDomainName,
ClangImporter::Implementation &importer) {
auto &clangSema = importer.getClangSema();
clang::IdentifierInfo *errorDomainDeclName =
&clangSema.getASTContext().Idents.get(errorDomainName);
clang::LookupResult lookupResult(
clangSema, clang::DeclarationName(errorDomainDeclName),
clang::SourceLocation(), clang::Sema::LookupNameKind::LookupOrdinaryName);
if (!clangSema.LookupName(lookupResult, clangSema.TUScope)) {
// Couldn't actually import it as an error enum, fall back to enum
return false;
}
auto clangNamedDecl = lookupResult.getAsSingle<clang::NamedDecl>();
if (!clangNamedDecl) {
// Couldn't actually import it as an error enum, fall back to enum
return false;
}
return addErrorDomain(swiftDecl, clangNamedDecl, importer);
}
/// Retrieve the property type as determined by the given accessor.
static clang::QualType
getAccessorPropertyType(const clang::FunctionDecl *accessor, bool isSetter,
std::optional<unsigned> selfIndex) {
// Simple case: the property type of the getter is in the return
// type.
if (!isSetter) return accessor->getReturnType();
// For the setter, first check that we have the right number of
// parameters.
unsigned numExpectedParams = selfIndex ? 2 : 1;
if (accessor->getNumParams() != numExpectedParams)
return clang::QualType();
// Dig out the parameter for the value.
unsigned valueIdx = selfIndex ? (1 - *selfIndex) : 0;
auto param = accessor->getParamDecl(valueIdx);
return param->getType();
}
/// Whether we should suppress importing the Objective-C generic type params
/// of this class as Swift generic type params.
static bool
shouldSuppressGenericParamsImport(const LangOptions &langOpts,
const clang::ObjCInterfaceDecl *decl) {
if (decl->hasAttr<clang::SwiftImportAsNonGenericAttr>())
return true;
// FIXME: This check is only necessary to keep things working even without
// the SwiftImportAsNonGeneric API note. Once we can guarantee that that
// attribute is present in all contexts, we can remove this check.
auto isFromFoundationModule = [](const clang::Decl *decl) -> bool {
clang::Module *module = getClangSubmoduleForDecl(decl).value();
if (!module)
return false;
return module->getTopLevelModuleName() == "Foundation";
};
if (isFromFoundationModule(decl)) {
// In Swift 3 we used a hardcoded list of declarations, and made all of
// their subclasses drop their generic parameters when imported.
while (decl) {
StringRef name = decl->getName();
if (name == "NSArray" || name == "NSDictionary" || name == "NSSet" ||
name == "NSOrderedSet" || name == "NSEnumerator" ||
name == "NSMeasurement") {
return true;
}
decl = decl->getSuperClass();
}
}
return false;
}
/// Determine if the given Objective-C instance method should also
/// be imported as a class method.
///
/// Objective-C root class instance methods are also reflected as
/// class methods.
static bool shouldAlsoImportAsClassMethod(FuncDecl *method) {
// Only instance methods.
if (!method->isInstanceMember())
return false;
// Must be a method within a class or extension thereof.
auto classDecl = method->getDeclContext()->getSelfClassDecl();
if (!classDecl)
return false;
// The class must not have a superclass.
if (classDecl->hasSuperclass())
return false;
// There must not already be a class method with the same
// selector.
auto objcClass =
cast_or_null<clang::ObjCInterfaceDecl>(classDecl->getClangDecl());
if (!objcClass)
return false;
auto objcMethod = cast_or_null<clang::ObjCMethodDecl>(method->getClangDecl());
if (!objcMethod)
return false;
return !objcClass->getClassMethod(objcMethod->getSelector(),
/*AllowHidden=*/true);
}
static bool
classImplementsProtocol(const clang::ObjCInterfaceDecl *constInterface,
const clang::ObjCProtocolDecl *constProto,
bool checkCategories) {
auto interface = const_cast<clang::ObjCInterfaceDecl *>(constInterface);
auto proto = const_cast<clang::ObjCProtocolDecl *>(constProto);
return interface->ClassImplementsProtocol(proto, checkCategories);
}
static void
applyPropertyOwnership(VarDecl *prop,
clang::ObjCPropertyAttribute::Kind attrs) {
Type ty = prop->getInterfaceType();
if (auto innerTy = ty->getOptionalObjectType())
ty = innerTy;
if (!ty->is<GenericTypeParamType>() && !ty->isAnyClassReferenceType())
return;
ASTContext &ctx = prop->getASTContext();
if (attrs & clang::ObjCPropertyAttribute::kind_copy) {
prop->getAttrs().add(new (ctx) NSCopyingAttr(false));
return;
}
if (attrs & clang::ObjCPropertyAttribute::kind_weak) {
prop->getAttrs().add(new (ctx)
ReferenceOwnershipAttr(ReferenceOwnership::Weak));
prop->setInterfaceType(WeakStorageType::get(
prop->getInterfaceType(), ctx));
return;
}
if ((attrs & clang::ObjCPropertyAttribute::kind_assign) ||
(attrs & clang::ObjCPropertyAttribute::kind_unsafe_unretained)) {
prop->getAttrs().add(
new (ctx) ReferenceOwnershipAttr(ReferenceOwnership::Unmanaged));
prop->setInterfaceType(UnmanagedStorageType::get(
prop->getInterfaceType(), ctx));
return;
}
}
/// Does this name refer to a method that might shadow Swift.print?
///
/// As a heuristic, methods that have a base name of 'print' but more than
/// one argument are left alone. These can still shadow Swift.print but are
/// less likely to be confused for it, at least.
static bool isPrintLikeMethod(DeclName name, const DeclContext *dc) {
if (!name || name.isSpecial() || name.isSimpleName())
return false;
if (name.getBaseName().userFacingName() != "print")
return false;
if (!dc->isTypeContext())
return false;
if (name.getArgumentNames().size() > 1)
return false;
return true;
}
using MirroredMethodEntry =
std::tuple<const clang::ObjCMethodDecl*, ProtocolDecl*, bool /*isAsync*/>;
ImportedType findOptionSetType(clang::QualType type,
ClangImporter::Implementation &Impl) {
ImportedType importedType;
auto fieldType = type;
if (auto elaborated = dyn_cast<clang::ElaboratedType>(fieldType))
fieldType = elaborated->desugar();
if (auto typedefType = dyn_cast<clang::TypedefType>(fieldType)) {
if (Impl.isUnavailableInSwift(typedefType->getDecl())) {
if (auto clangEnum =
findAnonymousEnumForTypedef(Impl.SwiftContext, typedefType)) {
// If this fails, it means that we need a stronger predicate for
// determining the relationship between an enum and typedef.
assert(
clangEnum.value()->getIntegerType()->getCanonicalTypeInternal() ==
typedefType->getCanonicalTypeInternal());
if (auto swiftEnum = Impl.importDecl(*clangEnum, Impl.CurrentVersion)) {
importedType = {cast<TypeDecl>(swiftEnum)->getDeclaredInterfaceType(),
false};
}
}
}
}
return importedType;
}
static bool areRecordFieldsComplete(const clang::CXXRecordDecl *decl) {
for (const auto *f : decl->fields()) {
auto *fieldRecord = f->getType()->getAsCXXRecordDecl();
if (fieldRecord) {
if (!fieldRecord->isCompleteDefinition()) {
return false;
}
if (!areRecordFieldsComplete(fieldRecord))
return false;
}
}
for (const auto base : decl->bases()) {
if (auto *baseRecord = base.getType()->getAsCXXRecordDecl()) {
if (!areRecordFieldsComplete(baseRecord))
return false;
}
}
return true;
}
namespace {
/// Customized llvm::DenseMapInfo for storing borrowed APSInts.
struct APSIntRefDenseMapInfo {
static inline const llvm::APSInt *getEmptyKey() {
return llvm::DenseMapInfo<const llvm::APSInt *>::getEmptyKey();
}
static inline const llvm::APSInt *getTombstoneKey() {
return llvm::DenseMapInfo<const llvm::APSInt *>::getTombstoneKey();
}
static unsigned getHashValue(const llvm::APSInt *ptrVal) {
assert(ptrVal != getEmptyKey() && ptrVal != getTombstoneKey());
return llvm::hash_value(*ptrVal);
}
static bool isEqual(const llvm::APSInt *lhs, const llvm::APSInt *rhs) {
if (lhs == rhs) return true;
if (lhs == getEmptyKey() || rhs == getEmptyKey()) return false;
if (lhs == getTombstoneKey() || rhs == getTombstoneKey()) return false;
return *lhs == *rhs;
}
};
/// Search the member tables for this class and its superclasses and try to
/// identify the nearest VarDecl that serves as a base for an override. We
/// have to do this ourselves because Objective-C has no semantic notion of
/// overrides, and freely allows users to refine the type of any member
/// property in a derived class.
///
/// The override must be the nearest possible one so there are not breaks
/// in the override chain. That is, suppose C refines B refines A and each
/// successively redeclares a member with a different type. It should be
/// the case that the nearest override from C is B and from B is A. If the
/// override point from C were A, then B would record an override on A as
/// well and we would introduce a semantic ambiguity.
///
/// There is also a special case for finding a method that stomps over a
/// getter. If this is the case and no override point is identified, we will
/// not import the property to force users to explicitly call the method.
static std::pair<VarDecl *, bool>
identifyNearestOverriddenDecl(ClangImporter::Implementation &Impl,
DeclContext *dc,
const clang::ObjCPropertyDecl *decl,
Identifier name,
ClassDecl *subject) {
bool foundMethod = false;
for (; subject; (subject = subject->getSuperclassDecl())) {
llvm::SmallVector<ValueDecl *, 8> lookup;
auto foundNames = Impl.MembersForNominal.find(subject);
if (foundNames != Impl.MembersForNominal.end()) {
auto foundDecls = foundNames->second.find(name);
if (foundDecls != foundNames->second.end()) {
lookup.append(foundDecls->second.begin(), foundDecls->second.end());
}
}
for (auto *&result : lookup) {
if (auto *fd = dyn_cast<FuncDecl>(result)) {
if (fd->isInstanceMember() != decl->isInstanceProperty())
continue;
// We only care about methods with no arguments, because they can
// shadow imported properties.
if (!fd->getName().getArgumentNames().empty())
continue;
// async methods don't conflict with properties because of sync/async
// overloading.
if (fd->hasAsync())
continue;
foundMethod = true;
} else if (auto *var = dyn_cast<VarDecl>(result)) {
if (var->isInstanceMember() != decl->isInstanceProperty())
continue;
// If the selectors of the getter match in Objective-C, we have an
// override.
if (var->getObjCGetterSelector() ==
Impl.importSelector(decl->getGetterName())) {
return {var, foundMethod};
}
}
}
}
return {nullptr, foundMethod};
}
// Attempt to identify the redeclaration of a property.
//
// Note that this function does not perform any additional member loading and
// is therefore subject to the relativistic effects of module import order.
// That is, suppose that a Clang Module and an Overlay module are in play.
// Depending on which module loads members first, a redeclaration point may
// or may not be identifiable.
VarDecl *
identifyPropertyRedeclarationPoint(ClangImporter::Implementation &Impl,
const clang::ObjCPropertyDecl *decl,
ClassDecl *subject, Identifier name) {
llvm::SetVector<Decl *> lookup;
// First, pull in all available members of the base class so we can catch
// redeclarations of APIs that are refined for Swift.
auto currentMembers = subject->getCurrentMembersWithoutLoading();
lookup.insert(currentMembers.begin(), currentMembers.end());
// Now pull in any just-imported members from the overrides table.
auto foundNames = Impl.MembersForNominal.find(subject);
if (foundNames != Impl.MembersForNominal.end()) {
auto foundDecls = foundNames->second.find(name);
if (foundDecls != foundNames->second.end()) {
lookup.insert(foundDecls->second.begin(), foundDecls->second.end());
}
}
for (auto *result : lookup) {
auto *var = dyn_cast<VarDecl>(result);
if (!var)
continue;
if (var->isInstanceMember() != decl->isInstanceProperty())
continue;
// If the selectors of the getter match in Objective-C, we have a
// redeclaration.
if (var->getObjCGetterSelector() ==
Impl.importSelector(decl->getGetterName())) {
return var;
}