-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathImporterImpl.h
1184 lines (994 loc) · 44 KB
/
ImporterImpl.h
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
//===--- ImporterImpl.h - Import Clang Modules - Implementation------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2015 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file provides the implementation class definitions for the Clang
// module loader.
//
//===----------------------------------------------------------------------===//
#ifndef SWIFT_CLANG_IMPORTER_IMPL_H
#define SWIFT_CLANG_IMPORTER_IMPL_H
#include "swift/ClangImporter/ClangImporter.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/LazyResolver.h"
#include "swift/AST/Module.h"
#include "swift/AST/Type.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/Basic/StringExtras.h"
#include "clang/APINotes/APINotesReader.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Frontend/CompilerInstance.h"
#include "clang/AST/Attr.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/TinyPtrVector.h"
#include <set>
namespace llvm {
class SmallBitVector;
}
namespace clang {
class APValue;
class Decl;
class DeclarationName;
class EnumDecl;
class MacroInfo;
class MangleContext;
class NamedDecl;
class ObjCInterfaceDecl;
class ObjCMethodDecl;
class ObjCPropertyDecl;
class ParmVarDecl;
class Parser;
class QualType;
class TypedefNameDecl;
}
namespace swift {
class ASTContext;
class ClangModuleUnit;
class ClassDecl;
class ConstructorDecl;
class Decl;
class DeclContext;
class Expr;
class ExtensionDecl;
class FuncDecl;
class Identifier;
class Pattern;
class SubscriptDecl;
class ValueDecl;
/// \brief Describes the kind of conversion to apply to a constant value.
enum class ConstantConvertKind {
/// \brief No conversion required.
None,
/// \brief Coerce the constant to the given type.
Coerce,
/// \brief Construct the given type from the constant value.
Construction,
/// \brief Construct the given type from the constant value, using an
/// optional initializer.
ConstructionWithUnwrap,
/// \brief Perform an unchecked downcast to the given type.
Downcast
};
/// \brief Describes the kind of type import we're performing.
enum class ImportTypeKind {
/// \brief Import a type in its most abstract form, without any adjustment.
Abstract,
/// \brief Import the underlying type of a typedef.
Typedef,
/// \brief Import the type of a literal value.
Value,
/// \brief Import the type of a literal value that can be bridged.
BridgedValue,
/// \brief Import the declared type of a variable.
Variable,
/// \brief Import the declared type of an audited variable.
///
/// This is exactly like ImportTypeKind::Variable, except it
/// disables wrapping CF class types in Unmanaged.
AuditedVariable,
/// \brief Import the declared type of a struct or union field.
RecordField,
/// \brief Import the result type of a function.
///
/// This provides special treatment for 'void', among other things, and
/// enables the conversion of bridged types.
Result,
/// \brief Import the result type of an audited function.
///
/// This is exactly like ImportTypeKind::Result, except it
/// disables wrapping CF class types in Unmanaged.
AuditedResult,
/// \brief Import the type of a function parameter.
///
/// This provides special treatment for C++ references (which become
/// [inout] parameters) and C pointers (which become magic [inout]-able types),
/// among other things, and enables the conversion of bridged types.
/// Parameters are always considered CF-audited.
Parameter,
/// \brief Import the type of a parameter declared with
/// \c CF_RETURNS_RETAINED.
///
/// This ensures that the parameter is not marked as Unmanaged.
CFRetainedOutParameter,
/// \brief Import the type of a parameter declared with
/// \c CF_RETURNS_NON_RETAINED.
///
/// This ensures that the parameter is not marked as Unmanaged.
CFUnretainedOutParameter,
/// \brief Import the type pointed to by a pointer or reference.
///
/// This provides special treatment for pointer-to-ObjC-pointer
/// types, which get imported as pointers to *checked* optional,
/// *Pointer<NSFoo?>, instead of implicitly unwrapped optional as usual.
Pointee,
/// \brief Import the type of an ObjC property.
///
/// This enables the conversion of bridged types. Properties are always
/// considered CF-audited.
Property,
/// \brief Import the type of an ObjC property accessor.
///
/// This behaves exactly like Property except that it accepts Void.
PropertyAccessor,
/// \brief Import the underlying type of an enum.
///
/// This provides special treatment for 'NSUInteger'.
Enum
};
/// \brief Describes the kind of the C type that can be mapped to a stdlib
/// swift type.
enum class MappedCTypeKind {
UnsignedInt,
SignedInt,
UnsignedWord,
SignedWord,
FloatIEEEsingle,
FloatIEEEdouble,
FloatX87DoubleExtended,
VaList,
ObjCBool,
ObjCSel,
ObjCId,
ObjCClass,
CGFloat,
Block,
};
/// \brief Describes what to do with the C name of a type that can be mapped to
/// a Swift standard library type.
enum class MappedTypeNameKind {
DoNothing,
DefineOnly,
DefineAndUse
};
/// \brief Describes certain kinds of methods that need to be specially
/// handled by the importer.
enum class SpecialMethodKind {
Regular,
Constructor,
PropertyAccessor,
NSDictionarySubscriptGetter
};
#define SWIFT_NATIVE_ANNOTATION_STRING "__swift native"
#define SWIFT_PROTOCOL_SUFFIX "Protocol"
#define SWIFT_CFTYPE_SUFFIX "Ref"
namespace api_notes = clang::api_notes;
using api_notes::FactoryAsInitKind;
/// \brief Implementation of the Clang importer.
class LLVM_LIBRARY_VISIBILITY ClangImporter::Implementation
: public LazyMemberLoader
{
friend class ClangImporter;
public:
/// \brief Describes how a particular C enumeration type will be imported
/// into Swift. All of the possibilities have the same storage
/// representation, but can be used in different ways.
enum class EnumKind {
/// \brief The enumeration type should map to an enum, which means that
/// all of the cases are independent.
Enum,
/// \brief The enumeration type should map to an option set, which means that
/// the constants represent combinations of independent flags.
Options,
/// \brief The enumeration type should map to a distinct type, but we don't
/// know the intended semantics of the enum constants, so conservatively
/// map them to independent constants.
Unknown,
/// \brief The enumeration constants should simply map to the appropriate
/// integer values.
Constants
};
Implementation(ASTContext &ctx, const ClangImporterOptions &opts);
~Implementation();
/// \brief Swift AST context.
ASTContext &SwiftContext;
const bool InferImplicitProperties;
const bool ImportForwardDeclarations;
const bool OmitNeedlessWords;
const bool InferDefaultArguments;
constexpr static const char * const moduleImportBufferName =
"<swift-imported-modules>";
constexpr static const char * const bridgingHeaderBufferName =
"<bridging-header-import>";
private:
/// \brief A count of the number of load module operations.
/// FIXME: Horrible, horrible hack for \c loadModule().
unsigned ImportCounter = 0;
/// \brief The value of \c ImportCounter last time when imported modules were
/// verified.
unsigned VerifiedImportCounter = 0;
/// \brief Clang compiler invocation.
llvm::IntrusiveRefCntPtr<clang::CompilerInvocation> Invocation;
/// \brief Clang compiler instance, which is used to actually load Clang
/// modules.
std::unique_ptr<clang::CompilerInstance> Instance;
/// \brief Clang compiler action, which is used to actually run the
/// parser.
std::unique_ptr<clang::FrontendAction> Action;
/// \brief Clang parser, which is used to load textual headers.
std::unique_ptr<clang::Parser> Parser;
/// \brief Clang parser, which is used to load textual headers.
std::unique_ptr<clang::MangleContext> Mangler;
/// The active type checker, or null if there is no active type checker.
///
/// The flag is \c true if there has ever been a type resolver assigned, i.e.
/// if type checking has begun.
llvm::PointerIntPair<LazyResolver *, 1, bool> typeResolver;
public:
/// \brief Mapping of already-imported declarations.
llvm::DenseMap<const clang::Decl *, Decl *> ImportedDecls;
/// \brief The set of "special" typedef-name declarations, which are
/// mapped to specific Swift types.
///
/// Normal typedef-name declarations imported into Swift will maintain
/// equality between the imported declaration's underlying type and the
/// import of the underlying type. A typedef-name declaration is special
/// when this is not the case, e.g., Objective-C's "BOOL" has an underlying
/// type of "signed char", but is mapped to a special Swift struct type
/// ObjCBool.
llvm::SmallDenseMap<const clang::TypedefNameDecl *, MappedTypeNameKind, 16>
SpecialTypedefNames;
/// Mapping from Objective-C selectors to method names.
llvm::DenseMap<std::pair<ObjCSelector, char>, DeclName> SelectorMappings;
/// Is the given identifier a reserved name in Swift?
static bool isSwiftReservedName(StringRef name);
/// Translation API nullability from an API note into an optional kind.
static OptionalTypeKind translateNullability(clang::NullabilityKind kind);
/// Retrieve the API notes readers that may contain information for the
/// given Objective-C container.
///
/// \returns a (name, primary, secondary) tuple containing the name of the
/// entity to look for and the API notes readers where information could be
/// found. The "primary" reader is the reader describes the module where the
/// specific container is defined; the "secondary" reader describes the
/// module in which the type is originally defined, if it's different from
/// the primary. Either or both of the readers may be null.
std::tuple<StringRef, api_notes::APINotesReader*, api_notes::APINotesReader*>
getAPINotesForContext(const clang::ObjCContainerDecl *container);
/// Retrieve the API notes reader that contains information for the
/// given declaration. Note, use getAPINotesForContext to get notes for ObjC
/// properties and methods.
api_notes::APINotesReader* getAPINotesForDecl(const clang::Decl *decl);
/// Retrieve any information known a priori about the given Objective-C
/// method, if we have it.
///
/// If \p container is specified, we're looking for a method with the same
/// selector and instance-ness in \p container.
Optional<api_notes::ObjCMethodInfo>
getKnownObjCMethod(const clang::ObjCMethodDecl *method,
const clang::ObjCContainerDecl *container = nullptr);
/// For ObjC property accessor, if the property is known, lookup
/// the property info and merge it in.
void mergePropInfoIntoAccessor(const clang::ObjCMethodDecl *method,
api_notes::ObjCMethodInfo &methodInfo);
/// Retrieve information about the given Objective-C context scoped to the
/// given Swift module.
Optional<api_notes::ObjCContextInfo>
getKnownObjCContext(const clang::ObjCContainerDecl *container);
/// Retrieve any information known a priori about the given Objective-C
/// property.
Optional<api_notes::ObjCPropertyInfo>
getKnownObjCProperty(const clang::ObjCPropertyDecl *property);
/// Retrieve any information known a priori about the given global variable.
Optional<api_notes::GlobalVariableInfo>
getKnownGlobalVariable(const clang::VarDecl *global);
/// Retrieve any information known a priori about the given global function.
Optional<api_notes::GlobalFunctionInfo>
getKnownGlobalFunction(const clang::FunctionDecl *function);
/// Determine whether the given class has designated initializers,
/// consulting
bool hasDesignatedInitializers(const clang::ObjCInterfaceDecl *classDecl);
/// Determine whether the given method is a designated initializer
/// of the given class.
bool isDesignatedInitializer(const clang::ObjCInterfaceDecl *classDecl,
const clang::ObjCMethodDecl *method);
/// Determine whether the given method is a required initializer
/// of the given class.
bool isRequiredInitializer(const clang::ObjCMethodDecl *method);
/// Determine whether the given class method should be imported as
/// an initializer.
FactoryAsInitKind getFactoryAsInit(const clang::ObjCInterfaceDecl *classDecl,
const clang::ObjCMethodDecl *method);
/// \brief Typedefs that we should not be importing. We should be importing
/// underlying decls instead.
llvm::DenseSet<const clang::Decl *> SuperfluousTypedefs;
/// Tag decls whose typedefs were imported instead.
///
/// \sa SuperfluousTypedefs
llvm::DenseSet<const clang::Decl *> DeclsWithSuperfluousTypedefs;
using ClangDeclAndFlag = llvm::PointerIntPair<const clang::Decl *, 1, bool>;
/// \brief Mapping of already-imported declarations from protocols, which
/// can (and do) get replicated into classes.
llvm::DenseMap<std::pair<ClangDeclAndFlag, DeclContext *>, Decl *>
ImportedProtocolDecls;
/// \brief Mapping of already-imported macros.
llvm::DenseMap<clang::MacroInfo *, ValueDecl *> ImportedMacros;
/// Keeps track of active selector-basde lookups, so that we don't infinitely
/// recurse when checking whether a method with a given selector has already
/// been imported.
llvm::DenseMap<std::pair<ObjCSelector, char>, unsigned>
ActiveSelectors;
// FIXME: An extra level of caching of visible decls, since lookup needs to
// be filtered by module after the fact.
SmallVector<ValueDecl *, 0> CachedVisibleDecls;
enum class CacheState {
Invalid,
InProgress,
Valid
} CurrentCacheState = CacheState::Invalid;
/// \brief Check if the declaration is one of the specially handled
/// accessibility APIs.
///
/// These appaer as both properties and methods in ObjC and should be
/// imported as methods into Swift.
bool isAccessibilityDecl(const clang::Decl *objCMethodOrProp);
private:
/// \brief Generation number that is used for crude versioning.
///
/// This value is incremented every time a new module is imported.
unsigned Generation = 1;
/// \brief A cached set of extensions for a particular Objective-C class.
struct CachedExtensions {
CachedExtensions()
: Extensions(nullptr), Generation(0) { }
CachedExtensions(const CachedExtensions &) = delete;
CachedExtensions &operator=(const CachedExtensions &) = delete;
CachedExtensions(CachedExtensions &&other)
: Extensions(other.Extensions), Generation(other.Generation)
{
other.Extensions = nullptr;
other.Generation = 0;
}
CachedExtensions &operator=(CachedExtensions &&other) {
delete Extensions;
Extensions = other.Extensions;
Generation = other.Generation;
other.Extensions = nullptr;
other.Generation = 0;
return *this;
}
~CachedExtensions() { delete Extensions; }
/// \brief The cached extensions.
SmallVector<ExtensionDecl *, 4> *Extensions;
/// \brief Generation number used to tell when this cache has gone stale.
unsigned Generation;
};
void bumpGeneration() {
++Generation;
SwiftContext.bumpGeneration();
CachedVisibleDecls.clear();
CurrentCacheState = CacheState::Invalid;
}
/// \brief Cache of the class extensions.
llvm::DenseMap<ClassDecl *, CachedExtensions> ClassExtensions;
public:
/// \brief Keep track of subscript declarations based on getter/setter
/// pairs.
llvm::DenseMap<std::pair<FuncDecl *, FuncDecl *>, SubscriptDecl *> Subscripts;
/// \brief Keep track of enum constant name prefixes in enums.
llvm::DenseMap<const clang::EnumDecl *, StringRef> EnumConstantNamePrefixes;
private:
class EnumConstantDenseMapInfo {
public:
using PairTy = std::pair<const clang::EnumDecl *, llvm::APSInt>;
using PointerInfo = llvm::DenseMapInfo<const clang::EnumDecl *>;
static inline PairTy getEmptyKey() {
return {PointerInfo::getEmptyKey(), llvm::APSInt(/*bitwidth=*/1)};
}
static inline PairTy getTombstoneKey() {
return {PointerInfo::getTombstoneKey(), llvm::APSInt(/*bitwidth=*/1)};
}
static unsigned getHashValue(const PairTy &pair) {
return llvm::combineHashValue(PointerInfo::getHashValue(pair.first),
llvm::hash_value(pair.second));
}
static bool isEqual(const PairTy &lhs, const PairTy &rhs) {
return lhs == rhs;
}
};
public:
/// \brief Keep track of enum constant values that have been imported.
llvm::DenseMap<std::pair<const clang::EnumDecl *, llvm::APSInt>,
EnumElementDecl *,
EnumConstantDenseMapInfo>
EnumConstantValues;
/// \brief Keep track of initializer declarations that correspond to
/// imported methods.
llvm::DenseMap<std::pair<const clang::ObjCMethodDecl *, DeclContext *>,
ConstructorDecl *>
Constructors;
private:
/// \brief NSObject, imported into Swift.
Type NSObjectTy;
/// A pair containing a ClangModuleUnit,
/// and whether the adapters of its re-exported modules have all been forced
/// to load already.
using ModuleInitPair = llvm::PointerIntPair<ClangModuleUnit *, 1, bool>;
public:
/// A map from Clang modules to their Swift wrapper modules.
llvm::SmallDenseMap<const clang::Module *, ModuleInitPair, 16> ModuleWrappers;
/// A map from Clang modules to their associated API notes.
llvm::SmallDenseMap<
const clang::Module *,
std::unique_ptr<api_notes::APINotesReader>> APINotesReaders;
/// The module unit that contains declarations from imported headers.
ClangModuleUnit *ImportedHeaderUnit = nullptr;
/// The modules re-exported by imported headers.
llvm::SmallVector<Module::ImportedModule, 8> ImportedHeaderExports;
/// The modules that requested imported headers.
///
/// These are used to look up Swift classes forward-declared with \@class.
TinyPtrVector<Module *> ImportedHeaderOwners;
/// \brief Clang's objectAtIndexedSubscript: selector.
clang::Selector objectAtIndexedSubscript;
/// \brief Clang's setObjectAt:indexedSubscript: selector.
clang::Selector setObjectAtIndexedSubscript;
/// \brief Clang's objectForKeyedSubscript: selector.
clang::Selector objectForKeyedSubscript;
/// \brief Clang's setObject:forKeyedSubscript: selector.
clang::Selector setObjectForKeyedSubscript;
private:
Optional<Module *> checkedFoundationModule, checkedSIMDModule;
/// External Decls that we have imported but not passed to the ASTContext yet.
SmallVector<Decl *, 4> RegisteredExternalDecls;
/// Protocol conformances that may be missing witnesses.
SmallVector<NormalProtocolConformance *, 4> DelayedProtocolConformances;
unsigned NumCurrentImportingEntities = 0;
/// Mapping from delayed conformance IDs to the set of delayed
/// protocol conformances.
llvm::DenseMap<unsigned, SmallVector<ProtocolConformance *, 4>>
DelayedConformances;
/// The next delayed conformance ID to use with \c DelayedConformances.
unsigned NextDelayedConformanceID = 0;
/// The set of imported protocols for a declaration, used only to
/// load all members of the declaration.
llvm::DenseMap<const Decl *, SmallVector<ProtocolDecl *, 4>>
ImportedProtocols;
void startedImportingEntity();
void finishedImportingEntity();
void finishPendingActions();
void finishProtocolConformance(NormalProtocolConformance *conformance);
struct ImportingEntityRAII {
Implementation &Impl;
ImportingEntityRAII(Implementation &Impl) : Impl(Impl) {
Impl.startedImportingEntity();
}
~ImportingEntityRAII() {
Impl.finishedImportingEntity();
}
};
public:
/// A predicate that indicates if the given platform should be
/// considered for availability.
std::function<bool (StringRef PlatformName)>
PlatformAvailabilityFilter;
/// A predicate that indicates if the given platform version should
/// should be included in the cutoff of deprecated APIs marked unavailable.
std::function<bool (unsigned major, llvm::Optional<unsigned> minor)>
DeprecatedAsUnavailableFilter;
/// The message to embed for implicitly unavailability if a deprecated
/// API is now unavailable.
std::string DeprecatedAsUnavailableMessage;
/// Tracks top level decls from the bridging header.
std::vector<clang::Decl *> BridgeHeaderTopLevelDecls;
std::vector<llvm::PointerUnion<clang::ImportDecl *, ImportDecl *>>
BridgeHeaderTopLevelImports;
/// Tracks macro definitions from the bridging header.
std::vector<clang::IdentifierInfo *> BridgeHeaderMacros;
/// Tracks included headers from the bridging header.
llvm::DenseSet<const clang::FileEntry *> BridgeHeaderFiles;
void addBridgeHeaderTopLevelDecls(clang::Decl *D);
bool shouldIgnoreBridgeHeaderTopLevelDecl(clang::Decl *D);
public:
void registerExternalDecl(Decl *D) {
RegisteredExternalDecls.push_back(D);
}
void scheduleFinishProtocolConformance(NormalProtocolConformance *C) {
DelayedProtocolConformances.push_back(C);
}
/// \brief Retrieve the Clang AST context.
clang::ASTContext &getClangASTContext() const {
return Instance->getASTContext();
}
/// \brief Retrieve the Clang Sema object.
clang::Sema &getClangSema() const {
return Instance->getSema();
}
/// \brief Retrieve the Clang AST context.
clang::Preprocessor &getClangPreprocessor() const {
return Instance->getPreprocessor();
}
clang::CodeGenOptions &getClangCodeGenOpts() const {
return Instance->getCodeGenOpts();
}
/// Imports the given header contents into the Clang context.
bool importHeader(Module *adapter, StringRef headerName, SourceLoc diagLoc,
bool trackParsedSymbols,
std::unique_ptr<llvm::MemoryBuffer> contents);
/// Returns the redeclaration of \p D that contains its definition for any
/// tag type decl (struct, enum, or union) or Objective-C class or protocol.
///
/// Returns \c None if \p D is not a redeclarable type declaration.
/// Returns null if \p D is a redeclarable type, but it does not have a
/// definition yet.
Optional<const clang::Decl *>
getDefinitionForClangTypeDecl(const clang::Decl *D);
/// Returns the module \p D comes from, or \c None if \p D does not have
/// a valid associated module.
///
/// The returned module may be null (but not \c None) if \p D comes from
/// an imported header.
Optional<clang::Module *>
getClangSubmoduleForDecl(const clang::Decl *D,
bool allowForwardDeclaration = false);
/// \brief Retrieve the imported module that should contain the given
/// Clang decl.
ClangModuleUnit *getClangModuleForDecl(const clang::Decl *D,
bool allowForwardDeclaration = false);
/// Returns the module \p MI comes from, or \c None if \p MI does not have
/// a valid associated module.
///
/// The returned module may be null (but not \c None) if \p MI comes from
/// an imported header.
Optional<clang::Module *>
getClangSubmoduleForMacro(const clang::MacroInfo *MI);
ClangModuleUnit *getClangModuleForMacro(const clang::MacroInfo *MI);
/// Retrieve the type of an instance of the given Clang declaration context,
/// or a null type if the DeclContext does not have a correspinding type.
clang::QualType getClangDeclContextType(const clang::DeclContext *dc);
/// Determine the imported CF type for the given typedef-name, or the empty
/// string if this is not an imported CF type name.
StringRef getCFTypeName(const clang::TypedefNameDecl *decl);
/// Retrieve the type name of a Clang type for the purposes of
/// omitting unneeded words.
OmissionTypeName getClangTypeNameForOmission(clang::QualType type);
/// Omit needless words in a function name.
DeclName omitNeedlessWordsInFunctionName(
DeclName name,
ArrayRef<const clang::ParmVarDecl *> params,
clang::QualType resultType,
const clang::DeclContext *dc,
const llvm::SmallBitVector &nonNullArgs,
const Optional<api_notes::ObjCMethodInfo> &knownMethod,
Optional<unsigned> errorParamIndex,
bool returnsSelf,
bool isInstanceMethod);
/// \brief Converts the given Swift identifier for Clang.
clang::DeclarationName exportName(Identifier name);
/// Imports the name of the given Clang decl into Swift.
///
/// Note that this may result in a name different from the Clang name, so it
/// should not be used when referencing Clang symbols. (In particular, it
/// should not be put into \c \@objc attributes.)
///
/// \sa importName(clang::DeclarationName, StringRef)
Identifier importName(const clang::NamedDecl *D, StringRef removePrefix = "");
/// \brief Import the given Clang name into Swift.
///
/// \param name The Clang name to map into Swift.
///
/// \param removePrefix The prefix to remove from the Clang name to produce
/// the Swift name. If the Clang name does not start with this prefix,
/// nothing is removed.
Identifier importDeclName(clang::DeclarationName name,
StringRef removePrefix = "");
/// Import an Objective-C selector.
ObjCSelector importSelector(clang::Selector selector);
/// Import a Swift name as a Clang selector.
clang::Selector exportSelector(DeclName name, bool allowSimpleName = true);
/// Export a Swift Objective-C selector as a Clang Objective-C selector.
clang::Selector exportSelector(ObjCSelector selector);
/// Map the given selector to a declaration name.
///
/// \param selector The selector to map.
///
/// \param isInitializer Whether this name should be mapped as an
/// initializer.
///
/// \param isSwiftPrivate Whether this name is for a declaration marked with
/// the 'swift_private' attribute.
DeclName mapSelectorToDeclName(ObjCSelector selector, bool isInitializer,
bool isSwiftPrivate);
/// Try to map the given selector, which may be the name of a factory method,
/// to the name of an initializer.
///
/// \param selector The selector to map.
///
/// \param className The name of the class in which the method occurs.
///
/// \param isSwiftPrivate Whether this name is for a declaration marked with
/// the 'swift_private' attribute.
///
/// \returns the initializer name for this factory method, or an empty
/// name if this selector does not fit the pattern.
DeclName mapFactorySelectorToInitializerName(ObjCSelector selector,
StringRef className,
bool isSwiftPrivate);
/// \brief Import the given Swift source location into Clang.
clang::SourceLocation exportSourceLoc(SourceLoc loc);
/// \brief Import the given Clang source location into Swift.
SourceLoc importSourceLoc(clang::SourceLocation loc);
/// \brief Import the given Clang source range into Swift.
SourceRange importSourceRange(clang::SourceRange loc);
/// \brief Import the given Clang preprocessor macro as a Swift value decl.
///
/// \returns The imported declaration, or null if the macro could not be
/// translated into Swift.
ValueDecl *importMacro(Identifier name, clang::MacroInfo *macro);
/// Returns true if it is expected that the macro is ignored.
bool shouldIgnoreMacro(StringRef name, const clang::MacroInfo *macro);
/// \brief Classify the given Clang enumeration type to describe how it
/// should be imported
EnumKind classifyEnum(const clang::EnumDecl *decl);
/// Import attributes from the given Clang declaration to its Swift
/// equivalent.
///
/// \param ClangDecl The decl being imported.
/// \param MappedDecl The decl to attach attributes to.
/// \param NewContext If present, the Clang node for the context the decl is
/// being imported into, which may affect info from API notes.
void importAttributes(const clang::NamedDecl *ClangDecl, Decl *MappedDecl,
const clang::ObjCContainerDecl *NewContext = nullptr);
/// If we already imported a given decl, return the corresponding Swift decl.
/// Otherwise, return nullptr.
Decl *importDeclCached(const clang::NamedDecl *ClangDecl);
Decl *importDeclImpl(const clang::NamedDecl *ClangDecl,
bool &TypedefIsSuperfluous,
bool &HadForwardDeclaration);
Decl *importDeclAndCacheImpl(const clang::NamedDecl *ClangDecl,
bool SuperfluousTypedefsAreTransparent);
/// \brief Same as \c importDeclReal, but for use inside importer
/// implementation.
///
/// Unlike \c importDeclReal, this function for convenience transparently
/// looks through superfluous typedefs and returns the imported underlying
/// decl in that case.
Decl *importDecl(const clang::NamedDecl *ClangDecl) {
return importDeclAndCacheImpl(ClangDecl,
/*SuperfluousTypedefsAreTransparent=*/true);
}
/// \brief Import the given Clang declaration into Swift. Use this function
/// outside of the importer implementation, when importing a decl requested by
/// Swift code.
///
/// \returns The imported declaration, or null if this declaration could
/// not be represented in Swift.
Decl *importDeclReal(const clang::NamedDecl *ClangDecl) {
return importDeclAndCacheImpl(ClangDecl,
/*SuperfluousTypedefsAreTransparent=*/false);
}
/// \brief Import a cloned version of the given declaration, which is part of
/// an Objective-C protocol and currently must be a method or property, into
/// the given declaration context.
///
/// \returns The imported declaration, or null if this declaration could not
/// be represented in Swift.
Decl *importMirroredDecl(const clang::NamedDecl *decl, DeclContext *dc,
ProtocolDecl *proto, bool forceClassMethod = false);
/// \brief Import the given Clang declaration context into Swift.
///
/// Usually one will use \c importDeclContextOf instead.
///
/// \returns The imported declaration context, or null if it could not
/// be converted.
DeclContext *importDeclContextImpl(const clang::DeclContext *dc);
/// \brief Import the declaration context of a given Clang declaration into
/// Swift.
///
/// \returns The imported declaration context, or null if it could not
/// be converted.
DeclContext *importDeclContextOf(const clang::Decl *D);
/// \brief Create a new named constant with the given value.
///
/// \param name The name of the constant.
/// \param dc The declaration context into which the name will be introduced.
/// \param type The type of the named constant.
/// \param value The value of the named constant.
/// \param convertKind How to convert the constant to the given type.
/// \param isStatic Whether the constant should be a static member of \p dc.
ValueDecl *createConstant(Identifier name, DeclContext *dc,
Type type, const clang::APValue &value,
ConstantConvertKind convertKind,
bool isStatic,
ClangNode ClangN);
/// \brief Create a new named constant with the given value.
///
/// \param name The name of the constant.
/// \param dc The declaration context into which the name will be introduced.
/// \param type The type of the named constant.
/// \param value The value of the named constant.
/// \param convertKind How to convert the constant to the given type.
/// \param isStatic Whether the constant should be a static member of \p dc.
ValueDecl *createConstant(Identifier name, DeclContext *dc,
Type type, StringRef value,
ConstantConvertKind convertKind,
bool isStatic,
ClangNode ClangN);
/// \brief Create a new named constant using the given expression.
///
/// \param name The name of the constant.
/// \param dc The declaration context into which the name will be introduced.
/// \param type The type of the named constant.
/// \param valueExpr An expression to use as the value of the constant.
/// \param convertKind How to convert the constant to the given type.
/// \param isStatic Whether the constant should be a static member of \p dc.
ValueDecl *createConstant(Identifier name, DeclContext *dc,
Type type, Expr *valueExpr,
ConstantConvertKind convertKind,
bool isStatic,
ClangNode ClangN);
/// \brief Add "Unavailable" annotation to the swift declaration.
void markUnavailable(ValueDecl *decl, StringRef unavailabilityMsg);
/// \brief Create a decl with error type and an "unavailable" attribute on it
/// with the specified message.
ValueDecl *createUnavailableDecl(Identifier name, DeclContext *dc,
Type type, StringRef UnavailableMessage,
bool isStatic, ClangNode ClangN);
/// \brief Retrieve the standard library module.
Module *getStdlibModule();
/// \brief Retrieve the named module.
///
/// \param name The name of the module.
///
/// \returns The named module, or null if the module has not been imported.
Module *getNamedModule(StringRef name);
/// \brief Returns the "Foundation" module, if it can be loaded.
///
/// After this has been called, the Foundation module will or won't be loaded
/// into the ASTContext.
Module *tryLoadFoundationModule();
/// \brief Returns the "SIMD" module, if it can be loaded.
///
/// After this has been called, the SIMD module will or won't be loaded
/// into the ASTContext.
Module *tryLoadSIMDModule();
/// \brief Retrieves the Swift wrapper for the given Clang module, creating
/// it if necessary.
ClangModuleUnit *getWrapperForModule(ClangImporter &importer,
const clang::Module *underlying);
/// Retrieve the API notes reader that corresponds to the given Clang module,
/// loading it if necessary.
///
/// \returns an unowned pointer to the corresponding API notes reader, or
/// nullptr if no API notes file exists.
api_notes::APINotesReader *getAPINotesForModule(const clang::Module *module);
/// \brief Constructs a Swift module for the given Clang module.
Module *finishLoadingClangModule(ClangImporter &importer,
const clang::Module *clangModule,
bool preferAdapter);
/// \brief Retrieve the named Swift type, e.g., Int32.
///
/// \param module The name of the module in which the type should occur.
///
/// \param name The name of the type to find.
///
/// \returns The named type, or null if the type could not be found.
Type getNamedSwiftType(Module *module, StringRef name);
/// \brief Retrieve a specialization of the named Swift type, e.g.,
/// UnsafeMutablePointer<T>.
///
/// \param module The name of the module in which the type should occur.
///
/// \param name The name of the type to find.
///
/// \param args The arguments to use in the specialization.
///
/// \returns The named type, or null if the type could not be found.
Type getNamedSwiftTypeSpecialization(Module *module, StringRef name,
ArrayRef<Type> args);
/// \brief Retrieve the NSObject type.
Type getNSObjectType();
/// \brief Retrieve the NSObject protocol type.
Type getNSObjectProtocolType();
/// \brief Retrieve the NSCopying protocol type.
Type getNSCopyingType();
/// \brief Retrieve the CFStringRef typealias.
Type getCFStringRefType();
/// \brief Determines whether the given type matches an implicit type
/// bound of "NSObject", which is used to validate NSDictionary/NSSet.
bool matchesNSObjectBound(Type type);
/// \brief Look up and attempt to import a Clang declaration with
/// the given name.
Decl *importDeclByName(StringRef name);
/// \brief Import the given Clang type into Swift.
///
/// \param type The Clang type to import.
///
/// \param kind The kind of type import we're performing.
///
/// \param allowNSUIntegerAsInt If true, NSUInteger will be imported as Int
/// in certain contexts. If false, it will always be imported as UInt.