forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImportName.cpp
1888 lines (1625 loc) · 67.3 KB
/
ImportName.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
//===--- ImportName.cpp - Imported Swift names for Clang decls ------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 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 provides class definitions for naming-related concerns in the
// ClangImporter.
//
//===----------------------------------------------------------------------===//
#include "CFTypeInfo.h"
#include "IAMInference.h"
#include "ImporterImpl.h"
#include "ClangDiagnosticConsumer.h"
#include "swift/Subsystems.h"
#include "swift/AST/ASTContext.h"
#include "swift/AST/DiagnosticEngine.h"
#include "swift/AST/DiagnosticsClangImporter.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/Types.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/StringExtras.h"
#include "swift/ClangImporter/ClangImporterOptions.h"
#include "swift/Parse/Parser.h"
#include "clang/AST/ASTContext.h"
#include "clang/Basic/IdentifierTable.h"
#include "clang/Basic/Module.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Parse/Parser.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Sema.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <memory>
#include "llvm/ADT/Statistic.h"
#define DEBUG_TYPE "Import Name"
STATISTIC(ImportNameNumCacheHits, "# of times the import name cache was hit");
STATISTIC(ImportNameNumCacheMisses, "# of times the import name cache was missed");
using namespace swift;
using namespace importer;
// Commonly-used Clang classes.
using clang::CompilerInstance;
using clang::CompilerInvocation;
/// Determine whether the given Clang selector matches the given
/// selector pieces.
static bool isNonNullarySelector(clang::Selector selector,
ArrayRef<StringRef> pieces) {
unsigned n = selector.getNumArgs();
if (n == 0) return false;
if (n != pieces.size()) return false;
for (unsigned i = 0; i != n; ++i) {
if (selector.getNameForSlot(i) != pieces[i]) return false;
}
return true;
}
/// Whether we should make a variadic method with the given selector
/// non-variadic.
static bool shouldMakeSelectorNonVariadic(clang::Selector selector) {
// This is UIActionSheet's designated initializer.
if (isNonNullarySelector(selector,
{ "initWithTitle",
"delegate",
"cancelButtonTitle",
"destructiveButtonTitle",
"otherButtonTitles" }))
return true;
// This is UIAlertView's designated initializer.
if (isNonNullarySelector(selector,
{ "initWithTitle",
"message",
"delegate",
"cancelButtonTitle",
"otherButtonTitles" }))
return true;
// Nothing else for now.
return false;
}
static bool isBlockParameter(const clang::ParmVarDecl *param) {
return param->getType()->isBlockPointerType();
}
static bool isErrorOutParameter(const clang::ParmVarDecl *param,
ForeignErrorConvention::IsOwned_t &isErrorOwned) {
clang::QualType type = param->getType();
// Must be a pointer.
auto ptrType = type->getAs<clang::PointerType>();
if (!ptrType) return false;
type = ptrType->getPointeeType();
// For NSError**, take ownership from the qualifier.
if (auto objcPtrType = type->getAs<clang::ObjCObjectPointerType>()) {
auto iface = objcPtrType->getInterfaceDecl();
if (iface && iface->getName() == "NSError") {
switch (type.getObjCLifetime()) {
case clang::Qualifiers::OCL_None:
llvm_unreachable("not in ARC?");
case clang::Qualifiers::OCL_ExplicitNone:
case clang::Qualifiers::OCL_Autoreleasing:
isErrorOwned = ForeignErrorConvention::IsNotOwned;
return true;
case clang::Qualifiers::OCL_Weak:
// We just don't know how to handle this.
return false;
case clang::Qualifiers::OCL_Strong:
isErrorOwned = ForeignErrorConvention::IsOwned;
return false;
}
llvm_unreachable("bad error ownership");
}
}
return false;
}
static bool isBoolType(clang::ASTContext &ctx, clang::QualType type) {
do {
// Check whether we have a typedef for "BOOL" or "Boolean".
if (auto typedefType = dyn_cast<clang::TypedefType>(type.getTypePtr())) {
auto typedefDecl = typedefType->getDecl();
if (typedefDecl->getName() == "BOOL" ||
typedefDecl->getName() == "Boolean")
return true;
type = typedefDecl->getUnderlyingType();
continue;
}
// Try to desugar one level...
clang::QualType desugared = type.getSingleStepDesugaredType(ctx);
if (desugared.getTypePtr() == type.getTypePtr())
break;
type = desugared;
} while (!type.isNull());
return false;
}
static bool isIntegerType(clang::QualType clangType) {
if (auto builtinTy = clangType->getAs<clang::BuiltinType>()) {
return (builtinTy->getKind() >= clang::BuiltinType::Bool &&
builtinTy->getKind() <= clang::BuiltinType::UInt128) ||
(builtinTy->getKind() >= clang::BuiltinType::SChar &&
builtinTy->getKind() <= clang::BuiltinType::Int128);
}
return false;
}
/// Whether the given Objective-C type can be imported as an optional type.
static bool canImportAsOptional(clang::ASTContext &ctx, clang::QualType type) {
// Note: this mimics ImportHint::canImportAsOptional.
// Objective-C object pointers.
if (type->getAs<clang::ObjCObjectPointerType>()) return true;
// Block and C pointers, including CF types.
if (type->isBlockPointerType() || type->isPointerType()) return true;
return false;
}
static Optional<ForeignErrorConvention::Kind>
classifyMethodErrorHandling(const clang::ObjCMethodDecl *clangDecl,
OptionalTypeKind resultOptionality) {
// TODO: opt out any non-standard methods here?
clang::ASTContext &clangCtx = clangDecl->getASTContext();
// Check for an explicit attribute.
if (auto attr = clangDecl->getAttr<clang::SwiftErrorAttr>()) {
switch (attr->getConvention()) {
case clang::SwiftErrorAttr::None:
return None;
case clang::SwiftErrorAttr::NonNullError:
return ForeignErrorConvention::NonNilError;
// Only honor null_result if we actually imported as a
// non-optional type.
case clang::SwiftErrorAttr::NullResult:
if (resultOptionality != OTK_None &&
canImportAsOptional(clangCtx, clangDecl->getReturnType()))
return ForeignErrorConvention::NilResult;
return None;
// Preserve the original result type on a zero_result unless we
// imported it as Bool.
case clang::SwiftErrorAttr::ZeroResult:
if (isBoolType(clangCtx, clangDecl->getReturnType())) {
return ForeignErrorConvention::ZeroResult;
} else if (isIntegerType(clangDecl->getReturnType())) {
return ForeignErrorConvention::ZeroPreservedResult;
}
return None;
// There's no reason to do the same for nonzero_result because the
// only meaningful value remaining would be zero.
case clang::SwiftErrorAttr::NonZeroResult:
if (isIntegerType(clangDecl->getReturnType()))
return ForeignErrorConvention::NonZeroResult;
return None;
}
llvm_unreachable("bad swift_error kind");
}
// Otherwise, apply the default rules.
// For bool results, a zero value is an error.
if (isBoolType(clangCtx, clangDecl->getReturnType())) {
return ForeignErrorConvention::ZeroResult;
}
// For optional reference results, a nil value is normally an error.
if (resultOptionality != OTK_None &&
canImportAsOptional(clangCtx, clangDecl->getReturnType())) {
return ForeignErrorConvention::NilResult;
}
return None;
}
static const char ErrorSuffix[] = "AndReturnError";
static const char AltErrorSuffix[] = "WithError";
/// Determine the optionality of the given Objective-C method.
///
/// \param method The Clang method.
static OptionalTypeKind getResultOptionality(
const clang::ObjCMethodDecl *method) {
auto &clangCtx = method->getASTContext();
// If nullability is available on the type, use it.
if (auto nullability = method->getReturnType()->getNullability(clangCtx)) {
return translateNullability(*nullability);
}
// If there is a returns_nonnull attribute, non-null.
if (method->hasAttr<clang::ReturnsNonNullAttr>())
return OTK_None;
// Default to implicitly unwrapped optionals.
return OTK_ImplicitlyUnwrappedOptional;
}
/// \brief Determine whether the given name is reserved for Swift.
static bool isSwiftReservedName(StringRef name) {
tok kind = Lexer::kindOfIdentifier(name, /*InSILMode=*/false);
return (kind != tok::identifier);
}
/// Determine whether we should lowercase the first word of the given value
/// name.
static bool shouldLowercaseValueName(StringRef name) {
// If we see any lowercase characters, we can lowercase.
for (auto c : name) {
if (clang::isLowercase(c)) return true;
}
// Otherwise, lowercasing will either be a no-op or we have ALL_CAPS.
return false;
}
/// Will recursively print out the fully qualified context for the given name.
/// Ends with a trailing "."
static void printFullContextPrefix(ImportedName name, ImportNameVersion version,
llvm::raw_ostream &os,
ClangImporter::Implementation &Impl) {
const clang::NamedDecl *newDeclContextNamed = nullptr;
switch (name.getEffectiveContext().getKind()) {
case EffectiveClangContext::UnresolvedContext:
os << name.getEffectiveContext().getUnresolvedName() << ".";
// And we're done!
return;
case EffectiveClangContext::DeclContext: {
auto namedDecl = dyn_cast<clang::NamedDecl>(
name.getEffectiveContext().getAsDeclContext());
if (!namedDecl) {
// We're done
return;
}
newDeclContextNamed = cast<clang::NamedDecl>(namedDecl);
break;
}
case EffectiveClangContext::TypedefContext:
newDeclContextNamed = name.getEffectiveContext().getTypedefName();
break;
}
// Now, let's print out the parent
assert(newDeclContextNamed && "should of been set");
auto parentName = Impl.importFullName(newDeclContextNamed, version);
printFullContextPrefix(parentName, version, os, Impl);
os << parentName.getDeclName() << ".";
}
void ClangImporter::Implementation::printSwiftName(ImportedName name,
ImportNameVersion version,
bool fullyQualified,
llvm::raw_ostream &os) {
// Property accessors.
bool isGetter = false;
bool isSetter = false;
switch (name.getAccessorKind()) {
case ImportedAccessorKind::None:
break;
case ImportedAccessorKind::PropertyGetter:
case ImportedAccessorKind::SubscriptGetter:
os << "getter:";
isGetter = true;
break;
case ImportedAccessorKind::PropertySetter:
case ImportedAccessorKind::SubscriptSetter:
os << "setter:";
isSetter = true;
break;
}
if (fullyQualified)
printFullContextPrefix(name, version, os, *this);
// Base name.
os << name.getDeclName().getBaseName();
// Determine the number of argument labels we'll be producing.
auto argumentNames = name.getDeclName().getArgumentNames();
unsigned numArguments = argumentNames.size();
if (name.getSelfIndex()) ++numArguments;
if (isSetter) ++numArguments;
// If the result is a simple name that is not a getter, we're done.
if (numArguments == 0 && name.getDeclName().isSimpleName() && !isGetter)
return;
// We need to produce a function name.
os << "(";
unsigned currentArgName = 0;
for (unsigned i = 0; i != numArguments; ++i) {
// The "self" parameter.
if (name.getSelfIndex() && *name.getSelfIndex() == i) {
os << "self:";
continue;
}
if (currentArgName < argumentNames.size()) {
if (argumentNames[currentArgName].empty())
os << "_";
else
os << argumentNames[currentArgName].str();
os << ":";
++currentArgName;
continue;
}
// We don't have a name for this argument.
os << "_:";
}
os << ")";
}
/// Retrieve the name of the given Clang declaration context for
/// printing.
static StringRef getClangDeclContextName(const clang::DeclContext *dc) {
auto type = getClangDeclContextType(dc);
if (type.isNull()) return StringRef();
return getClangTypeNameForOmission(dc->getParentASTContext(), type).Name;
}
namespace {
/// Merge the a set of imported names produced for the overridden
/// declarations of a given method or property.
template<typename DeclType>
void mergeOverriddenNames(ASTContext &ctx,
const DeclType *decl,
SmallVectorImpl<std::pair<const DeclType *,
ImportedName>>
&overriddenNames) {
typedef std::pair<const DeclType *, ImportedName> OverriddenName;
llvm::SmallPtrSet<DeclName, 4> known;
(void)known.insert(DeclName());
overriddenNames.erase(
std::remove_if(overriddenNames.begin(), overriddenNames.end(),
[&](OverriddenName overridden) {
return !known.insert(overridden.second.getDeclName())
.second;
}),
overriddenNames.end());
if (overriddenNames.size() < 2)
return;
// Complain about inconsistencies.
std::string nameStr;
auto method = dyn_cast<clang::ObjCMethodDecl>(decl);
if (method)
nameStr = method->getSelector().getAsString();
else
nameStr = cast<clang::ObjCPropertyDecl>(decl)->getName().str();
for (unsigned i = 1, n = overriddenNames.size(); i != n; ++i) {
ctx.Diags.diagnose(SourceLoc(), diag::inconsistent_swift_name,
method == nullptr,
nameStr,
getClangDeclContextName(decl->getDeclContext()),
overriddenNames[0].second,
getClangDeclContextName(
overriddenNames[0].first->getDeclContext()),
overriddenNames[i].second,
getClangDeclContextName(
overriddenNames[i].first->getDeclContext()));
}
}
} // end anonymous namespace
/// Skip a leading 'k' in a 'kConstant' pattern
static StringRef stripLeadingK(StringRef name) {
if (name.size() >= 2 && name[0] == 'k' &&
clang::isUppercase(name[1]))
return name.drop_front(1);
return name;
}
/// Strips a trailing "Notification", if present. Returns {} if name doesn't end
/// in "Notification", or it there would be nothing left.
StringRef importer::stripNotification(StringRef name) {
name = stripLeadingK(name);
StringRef notification = "Notification";
if (name.size() <= notification.size() || !name.endswith(notification))
return {};
return name.drop_back(notification.size());
}
/// Whether the decl is from a module who requested import-as-member inference
static bool moduleIsInferImportAsMember(const clang::NamedDecl *decl,
clang::Sema &clangSema) {
clang::Module *submodule;
if (auto m = decl->getImportedOwningModule()) {
submodule = m;
} else if (auto m = decl->getLocalOwningModule()) {
submodule = m;
} else if (auto m = clangSema.getPreprocessor().getCurrentModule()) {
submodule = m;
} else if (auto m = clangSema.getPreprocessor().getCurrentLexerSubmodule()) {
submodule = m;
} else {
return false;
}
while (submodule) {
if (submodule->IsSwiftInferImportAsMember) {
// HACK HACK HACK: This is a workaround for some module invalidation issue
// and inconsistency. This will go away soon.
return submodule->Name == "CoreGraphics";
}
submodule = submodule->Parent;
}
return false;
}
/// Match the name of the given Objective-C method to its enclosing class name
/// to determine the name prefix that would be stripped if the class method
/// were treated as an initializer.
static Optional<unsigned>
matchFactoryAsInitName(const clang::ObjCMethodDecl *method) {
// Only class methods can be mapped to initializers in this way.
if (!method->isClassMethod()) return None;
// Said class methods must be in an actual class.
auto objcClass = method->getClassInterface();
if (!objcClass) return None;
// See if we can match the class name to the beginning of the first
// selector piece.
auto firstPiece = method->getSelector().getNameForSlot(0);
if (firstPiece.empty())
return None;
StringRef firstArgLabel = matchLeadingTypeName(firstPiece,
objcClass->getName());
if (firstArgLabel.size() == firstPiece.size())
return None;
// FIXME: Factory methods cannot have dummy parameters added for
// historical reasons.
if (!firstArgLabel.empty() && method->getSelector().getNumArgs() == 0)
return None;
// Return the prefix length.
return firstPiece.size() - firstArgLabel.size();
}
/// Determine the kind of initializer the given factory method could be mapped
/// to, or produce \c None.
static Optional<CtorInitializerKind>
determineCtorInitializerKind(const clang::ObjCMethodDecl *method) {
// Determine whether we have a suitable return type.
if (method->hasRelatedResultType()) {
// When the factory method has an "instancetype" result type, we
// can import it as a convenience factory method.
return CtorInitializerKind::ConvenienceFactory;
}
if (auto objcPtr = method->getReturnType()
->getAs<clang::ObjCObjectPointerType>()) {
auto objcClass = method->getClassInterface();
if (!objcClass) return None;
if (objcPtr->getInterfaceDecl() != objcClass) {
// FIXME: Could allow a subclass here, but the rest of the compiler
// isn't prepared for that yet.
return None;
}
// Factory initializer.
return CtorInitializerKind::Factory;
}
// Not imported as an initializer.
return None;
}
namespace {
/// Aggregate struct for the common members of clang::SwiftVersionedAttr and
/// clang::SwiftVersionedRemovalAttr.
///
/// For a SwiftVersionedRemovalAttr, the Attr member will be null.
struct VersionedSwiftNameInfo {
const clang::SwiftNameAttr *Attr;
llvm::VersionTuple Version;
bool IsReplacedByActive;
};
/// The action to take upon seeing a particular versioned swift_name annotation.
enum class VersionedSwiftNameAction {
/// This annotation is not interesting.
Ignore,
/// This annotation is better than whatever we have so far.
Use,
/// This annotation is better than nothing, but that's all; don't bother
/// recording its version.
UseAsFallback,
/// This annotation itself isn't interesting, but its version shows that the
/// correct answer is whatever's currently active.
ResetToActive
};
} // end anonymous namespace
static VersionedSwiftNameAction
checkVersionedSwiftName(VersionedSwiftNameInfo info,
llvm::VersionTuple bestSoFar,
ImportNameVersion requestedVersion) {
if (!bestSoFar.empty() && bestSoFar <= info.Version)
return VersionedSwiftNameAction::Ignore;
auto requestedClangVersion = requestedVersion.asClangVersionTuple();
if (info.IsReplacedByActive) {
// We know that there are no versioned names between the active version and
// a replacement version, because otherwise /that/ name would be active.
// So if replacement < requested, we want to use the old value that was
// replaced (but with very low priority), and otherwise we want to use the
// new value that is now active. (Special case: replacement = 0 means that
// a header annotation was replaced by an unversioned API notes annotation.)
if (info.Version.empty() ||
info.Version >= requestedClangVersion) {
return VersionedSwiftNameAction::ResetToActive;
}
if (bestSoFar.empty())
return VersionedSwiftNameAction::UseAsFallback;
return VersionedSwiftNameAction::Ignore;
}
if (info.Version < requestedClangVersion)
return VersionedSwiftNameAction::Ignore;
return VersionedSwiftNameAction::Use;
}
static const clang::SwiftNameAttr *
findSwiftNameAttr(const clang::Decl *decl, ImportNameVersion version) {
#ifndef NDEBUG
if (Optional<const clang::Decl *> def = getDefinitionForClangTypeDecl(decl)) {
assert((*def == nullptr || *def == decl) &&
"swift_name should only appear on the definition");
}
#endif
if (version == ImportNameVersion::raw())
return nullptr;
// Handle versioned API notes for Swift 3 and later. This is the common case.
if (version > ImportNameVersion::swift2()) {
// FIXME: Until Apple gets a chance to update UIKit's API notes, always use
// the new name for certain properties.
if (auto *namedDecl = dyn_cast<clang::NamedDecl>(decl))
if (importer::isSpecialUIKitStructZeroProperty(namedDecl))
version = ImportNameVersion::swift4_2();
const auto *activeAttr = decl->getAttr<clang::SwiftNameAttr>();
const clang::SwiftNameAttr *result = activeAttr;
llvm::VersionTuple bestSoFar;
for (auto *attr : decl->attrs()) {
VersionedSwiftNameInfo info;
if (auto *versionedAttr = dyn_cast<clang::SwiftVersionedAttr>(attr)) {
auto *added =
dyn_cast<clang::SwiftNameAttr>(versionedAttr->getAttrToAdd());
if (!added)
continue;
info = {added, versionedAttr->getVersion(),
versionedAttr->getIsReplacedByActive()};
} else if (auto *removeAttr =
dyn_cast<clang::SwiftVersionedRemovalAttr>(attr)) {
if (removeAttr->getAttrKindToRemove() != clang::attr::SwiftName)
continue;
info = {nullptr, removeAttr->getVersion(),
removeAttr->getIsReplacedByActive()};
} else {
continue;
}
switch (checkVersionedSwiftName(info, bestSoFar, version)) {
case VersionedSwiftNameAction::Ignore:
continue;
case VersionedSwiftNameAction::Use:
result = info.Attr;
bestSoFar = info.Version;
break;
case VersionedSwiftNameAction::UseAsFallback:
// HACK: If there's a swift_name attribute in the headers /and/ in the
// unversioned API notes /and/ in the active versioned API notes, there
// will be two "replacement" attributes, one for each of the first two
// cases. Prefer the first one we see, because that turns out to be the
// one from the API notes, which matches the semantics when there are no
// versioned API notes. (This isn't very principled but there's at least
// a test to tell us if it changes.)
if (result == activeAttr)
result = info.Attr;
assert(bestSoFar.empty());
break;
case VersionedSwiftNameAction::ResetToActive:
result = activeAttr;
bestSoFar = info.Version;
break;
}
}
return result;
}
// The remainder of this function emulates the limited form of swift_name
// supported in Swift 2.
auto attr = decl->getAttr<clang::SwiftNameAttr>();
if (!attr) return nullptr;
// API notes produce attributes with no source location; ignore them because
// they weren't used for naming in Swift 2.
if (attr->getLocation().isInvalid()) return nullptr;
// Hardcode certain kinds of explicitly-written Swift names that were
// permitted and used in Swift 2. All others are ignored, so that we are
// assuming a more direct translation from the Objective-C APIs into Swift.
if (auto enumerator = dyn_cast<clang::EnumConstantDecl>(decl)) {
// Foundation's NSXMLDTDKind had an explicit swift_name attribute in
// Swift 2. Honor it.
if (enumerator->getName() == "NSXMLDTDKind") return attr;
return nullptr;
}
if (auto method = dyn_cast<clang::ObjCMethodDecl>(decl)) {
// Special case: mapping to an initializer.
if (attr->getName().startswith("init(")) {
// If we have a class method, honor the annotation to turn a class
// method into an initializer.
if (method->isClassMethod()) return attr;
return nullptr;
}
// Special case: preventing a mapping to an initializer.
if (matchFactoryAsInitName(method) && determineCtorInitializerKind(method))
return attr;
return nullptr;
}
return nullptr;
}
/// Determine whether the given class method should be imported as
/// an initializer.
static FactoryAsInitKind
getFactoryAsInit(const clang::ObjCInterfaceDecl *classDecl,
const clang::ObjCMethodDecl *method,
ImportNameVersion version) {
if (auto *customNameAttr = findSwiftNameAttr(method, version)) {
if (customNameAttr->getName().startswith("init("))
return FactoryAsInitKind::AsInitializer;
else
return FactoryAsInitKind::AsClassMethod;
}
return FactoryAsInitKind::Infer;
}
/// Determine whether this Objective-C method should be imported as
/// an initializer.
///
/// \param prefixLength Will be set to the length of the prefix that
/// should be stripped from the first selector piece, e.g., "init"
/// or the restated name of the class in a factory method.
///
/// \param kind Will be set to the kind of initializer being
/// imported. Note that this does not distinguish designated
/// vs. convenience; both will be classified as "designated".
static bool shouldImportAsInitializer(const clang::ObjCMethodDecl *method,
ImportNameVersion version,
unsigned &prefixLength,
CtorInitializerKind &kind) {
/// Is this an initializer?
if (isInitMethod(method)) {
prefixLength = 4;
kind = CtorInitializerKind::Designated;
return true;
}
// It must be a class method.
if (!method->isClassMethod()) return false;
// Said class methods must be in an actual class.
auto objcClass = method->getClassInterface();
if (!objcClass) return false;
// Check whether we should try to import this factory method as an
// initializer.
switch (getFactoryAsInit(objcClass, method, version)) {
case FactoryAsInitKind::AsInitializer:
// Okay; check for the correct result type below.
prefixLength = 0;
break;
case FactoryAsInitKind::Infer:
// See if we can match the class name to the beginning of the first
// selector piece.
if (auto matchedLength = matchFactoryAsInitName(method)) {
prefixLength = *matchedLength;
break;
}
return false;
case FactoryAsInitKind::AsClassMethod:
return false;
}
// Determine what kind of initializer we're creating.
if (auto initKind = determineCtorInitializerKind(method)) {
kind = *initKind;
return true;
}
// Not imported as an initializer.
return false;
}
/// Attempt to omit needless words from the given function name.
static bool omitNeedlessWordsInFunctionName(
StringRef &baseName, SmallVectorImpl<StringRef> &argumentNames,
ArrayRef<const clang::ParmVarDecl *> params, clang::QualType resultType,
const clang::DeclContext *dc, const llvm::SmallBitVector &nonNullArgs,
Optional<unsigned> errorParamIndex, bool returnsSelf, bool isInstanceMethod,
NameImporter &nameImporter) {
clang::ASTContext &clangCtx = nameImporter.getClangContext();
const version::Version &swiftLanguageVersion =
nameImporter.getLangOpts().EffectiveLanguageVersion;
// Collect the parameter type names.
StringRef firstParamName;
SmallVector<OmissionTypeName, 4> paramTypes;
for (unsigned i = 0, n = params.size(); i != n; ++i) {
auto param = params[i];
// Capture the first parameter name.
if (i == 0)
firstParamName = param->getName();
// Determine the number of parameters.
unsigned numParams = params.size();
if (errorParamIndex) --numParams;
bool isLastParameter
= (i == params.size() - 1) ||
(i == params.size() - 2 &&
errorParamIndex && *errorParamIndex == params.size() - 1);
// Figure out whether there will be a default argument for this
// parameter.
StringRef argumentName;
if (i < argumentNames.size())
argumentName = argumentNames[i];
bool hasDefaultArg =
ClangImporter::Implementation::inferDefaultArgument(
param->getType(),
getParamOptionality(swiftLanguageVersion, param,
!nonNullArgs.empty() && nonNullArgs[i]),
nameImporter.getIdentifier(baseName), numParams, argumentName,
i == 0, isLastParameter, nameImporter) != DefaultArgumentKind::None;
paramTypes.push_back(getClangTypeNameForOmission(clangCtx,
param->getOriginalType())
.withDefaultArgument(hasDefaultArg));
}
// Find the property names.
const InheritedNameSet *allPropertyNames = nullptr;
auto contextType = getClangDeclContextType(dc);
if (!contextType.isNull()) {
if (auto objcPtrType = contextType->getAsObjCInterfacePointerType())
if (auto objcClassDecl = objcPtrType->getInterfaceDecl())
allPropertyNames = nameImporter.getAllPropertyNames(
objcClassDecl, isInstanceMethod);
}
// Omit needless words.
return omitNeedlessWords(baseName, argumentNames, firstParamName,
getClangTypeNameForOmission(clangCtx, resultType),
getClangTypeNameForOmission(clangCtx, contextType),
paramTypes, returnsSelf, /*isProperty=*/false,
allPropertyNames, nameImporter.getScratch());
}
/// Prepare global name for importing onto a swift_newtype.
static StringRef determineSwiftNewtypeBaseName(StringRef baseName,
StringRef newtypeName,
bool &strippedPrefix) {
StringRef newBaseName = stripLeadingK(baseName);
if (newBaseName != baseName) {
baseName = newBaseName;
strippedPrefix = true;
}
// Special case: Strip Notification for NSNotificationName
auto stripped = stripNotification(baseName);
if (!stripped.empty())
return stripped;
bool nonIdentifier = false;
auto pre = getCommonWordPrefix(newtypeName, baseName, nonIdentifier);
if (pre.size()) {
baseName = baseName.drop_front(pre.size());
strippedPrefix = true;
}
return baseName;
}
EffectiveClangContext
NameImporter::determineEffectiveContext(const clang::NamedDecl *decl,
const clang::DeclContext *dc,
ImportNameVersion version) {
EffectiveClangContext res;
// Enumerators can end up within their enclosing enum or in the global
// scope, depending how their enclosing enumeration is imported.
if (isa<clang::EnumConstantDecl>(decl)) {
auto enumDecl = cast<clang::EnumDecl>(dc);
switch (getEnumKind(enumDecl)) {
case EnumKind::NonFrozenEnum:
case EnumKind::FrozenEnum:
case EnumKind::Options:
// Enums are mapped to Swift enums, Options to Swift option sets.
if (version != ImportNameVersion::raw()) {
res = cast<clang::DeclContext>(enumDecl);
break;
}
LLVM_FALLTHROUGH;
case EnumKind::Constants:
case EnumKind::Unknown:
// The enum constant goes into the redeclaration context of the
// enum.
res = enumDecl->getRedeclContext();
break;
}
// Import onto a swift_newtype if present
} else if (auto newtypeDecl = findSwiftNewtype(decl, clangSema, version)) {
res = newtypeDecl;
// Everything else goes into its redeclaration context.
} else {
res = dc->getRedeclContext();
}
// Anything in an Objective-C category or extension is adjusted to the
// class context.
if (auto category =
dyn_cast_or_null<clang::ObjCCategoryDecl>(res.getAsDeclContext())) {
// If the enclosing category is invalid, we cannot import the declaration.
if (category->isInvalidDecl())
return {};
return category->getClassInterface();
}
return res;
}
bool NameImporter::hasNamingConflict(const clang::NamedDecl *decl,
const clang::IdentifierInfo *proposedName,
const clang::TypedefNameDecl *cfTypedef) {
// Test to see if there is a value with the same name as 'proposedName'
// in the same module as the decl
// FIXME: This will miss macros.
auto clangModule = getClangSubmoduleForDecl(decl);
if (clangModule.hasValue() && clangModule.getValue())
clangModule = clangModule.getValue()->getTopLevelModule();
auto conflicts = [&](const clang::Decl *OtherD) -> bool {
// If these are simply redeclarations, they do not conflict.
if (decl->getCanonicalDecl() == OtherD->getCanonicalDecl())
return false;
// If we have a CF typedef, check whether the "other"
// declaration we found is just the opaque type behind it. If
// so, it does not conflict.
if (cfTypedef) {
if (auto cfPointerTy =
cfTypedef->getUnderlyingType()->getAs<clang::PointerType>()) {
if (auto tagDecl = cfPointerTy->getPointeeType()->getAsTagDecl()) {
if (tagDecl->getCanonicalDecl() == OtherD)
return false;
}
}
}
auto declModule = getClangSubmoduleForDecl(OtherD);
if (!declModule.hasValue())
return false;
// Handle the bridging header case. This is pretty nasty since things
// can get added to it *later*, but there's not much we can do.
if (!declModule.getValue())
return *clangModule == nullptr;
return *clangModule == declModule.getValue()->getTopLevelModule();
};
// Allow this lookup to find hidden names. We don't want the
// decision about whether to rename the decl to depend on
// what exactly the user has imported. Indeed, if we're being
// asked to resolve a serialization cross-reference, the user
// may not have imported this module at all, which means a
// normal lookup wouldn't even find the decl!
//
// Meanwhile, we don't need to worry about finding unwanted
// hidden declarations from different modules because we do a
// module check before deciding that there's a conflict.
clang::LookupResult lookupResult(clangSema, proposedName,
clang::SourceLocation(),
clang::Sema::LookupOrdinaryName);
lookupResult.setAllowHidden(true);
lookupResult.suppressDiagnostics();
if (clangSema.LookupName(lookupResult, /*scope=*/nullptr)) {
if (std::any_of(lookupResult.begin(), lookupResult.end(), conflicts))
return true;
}
lookupResult.clear(clang::Sema::LookupTagName);
if (clangSema.LookupName(lookupResult, /*scope=*/nullptr)) {
if (std::any_of(lookupResult.begin(), lookupResult.end(), conflicts))
return true;
}