Skip to content

Commit 8e96abd

Browse files
committed
[cxx-interop] Implicitly import Cxx module
This lifts the requirement for the user to explicitly add `import Cxx` in Swift code that relies on protocols from the `Cxx` module, such as `CxxSequence`.
1 parent fb1859d commit 8e96abd

File tree

3 files changed

+11
-15
lines changed

3 files changed

+11
-15
lines changed

lib/ClangImporter/ClangImporter.cpp

Lines changed: 11 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -3244,19 +3244,6 @@ static void getImportDecls(ClangModuleUnit *ClangUnit, const clang::Module *M,
32443244
auto *ID = createImportDecl(Ctx, ClangUnit, ImportedMod, Exported);
32453245
Results.push_back(ID);
32463246
}
3247-
3248-
if (Ctx.LangOpts.EnableCXXInterop && requiresCPlusPlus(M)) {
3249-
// Try to load the Cxx module. We don't use it directly here, but we need to
3250-
// make sure that ASTContext has loaded this module.
3251-
auto *cxxModule = Ctx.getModuleByIdentifier(Ctx.Id_Cxx);
3252-
if (cxxModule) {
3253-
ImportPath::Builder builder(Ctx.Id_Cxx);
3254-
auto *importCxx =
3255-
ImportDecl::create(Ctx, ClangUnit, SourceLoc(), ImportKind::Module,
3256-
SourceLoc(), builder.get());
3257-
Results.push_back(importCxx);
3258-
}
3259-
}
32603247
}
32613248

32623249
void ClangModuleUnit::getDisplayDecls(SmallVectorImpl<Decl*> &results, bool recursive) const {
@@ -3893,6 +3880,17 @@ void ClangModuleUnit::getImportedModulesForLookup(
38933880
} else {
38943881
clangModule->getExportedModules(imported);
38953882
topLevel = clangModule->getTopLevelModule();
3883+
3884+
// If this is a C++ module, implicitly import the Cxx module, which contains
3885+
// definitions of Swift protocols that C++ types might conform to, such as
3886+
// CxxSequence.
3887+
if (owner.SwiftContext.LangOpts.EnableCXXInterop &&
3888+
requiresCPlusPlus(clangModule)) {
3889+
auto *cxxModule =
3890+
owner.SwiftContext.getModuleByIdentifier(owner.SwiftContext.Id_Cxx);
3891+
if (cxxModule)
3892+
imports.push_back({ImportPath::Access(), cxxModule});
3893+
}
38963894
}
38973895

38983896
if (imported.empty()) {

test/Interop/Cxx/stdlib/overlay/custom-sequence-typechecker.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
// RUN: %target-typecheck-verify-swift -I %S/Inputs -enable-experimental-cxx-interop
22

33
import CustomSequence
4-
import Cxx
54

65
func checkIntSequence<S>(_ seq: S) where S: Sequence, S.Element == Int32 {
76
let contains = seq.contains(where: { $0 == 3 })

test/Interop/Cxx/stdlib/overlay/custom-sequence.swift

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55

66
import StdlibUnittest
77
import CustomSequence
8-
import Cxx
98

109
var CxxSequenceTestSuite = TestSuite("CxxSequence")
1110

0 commit comments

Comments
 (0)