Skip to content

[interop][SwiftToCxx] add initial C++14/17 generics support #61858

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Nov 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion lib/PrintAsClang/ClangSyntaxPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,15 @@ bool ClangSyntaxPrinter::printNominalTypeOutsideMemberDeclTemplateSpecifiers(
return false;
}

bool ClangSyntaxPrinter::printNominalTypeOutsideMemberDeclInnerStaticAssert(
const NominalTypeDecl *typeDecl) {
if (!typeDecl->isGeneric())
return true;
printGenericSignatureInnerStaticAsserts(
typeDecl->getGenericSignature().getCanonicalSignature());
return false;
}

void ClangSyntaxPrinter::printNominalClangTypeReference(
const clang::Decl *typeDecl) {
auto &clangCtx = typeDecl->getASTContext();
Expand Down Expand Up @@ -284,6 +293,7 @@ void ClangSyntaxPrinter::printGenericSignature(
printGenericTypeParamTypeName(genericParamType);
});
os << ">\n";
os << "#ifdef __cpp_concepts\n";
os << "requires ";
llvm::interleave(
signature.getInnermostGenericParams(), os,
Expand All @@ -293,7 +303,21 @@ void ClangSyntaxPrinter::printGenericSignature(
os << ">";
},
" && ");
os << "\n";
os << "\n#endif // __cpp_concepts\n";
}

void ClangSyntaxPrinter::printGenericSignatureInnerStaticAsserts(
const CanGenericSignature &signature) {
os << "#ifndef __cpp_concepts\n";
llvm::interleave(
signature.getInnermostGenericParams(), os,
[&](const GenericTypeParamType *genericParamType) {
os << "static_assert(swift::isUsableInGenericContext<";
printGenericTypeParamTypeName(genericParamType);
os << ">, \"type cannot be used in a Swift generic context\");";
},
"\n");
os << "\n#endif // __cpp_concepts\n";
}

void ClangSyntaxPrinter::printGenericSignatureParams(
Expand Down Expand Up @@ -358,3 +382,16 @@ void ClangSyntaxPrinter::printIncludeForShimHeader(StringRef headerName) {
void ClangSyntaxPrinter::printDefine(StringRef macroName) {
os << "#define " << macroName << "\n";
}

void ClangSyntaxPrinter::printIgnoredDiagnosticBlock(
StringRef diagName, llvm::function_ref<void()> bodyPrinter) {
os << "#pragma clang diagnostic push\n";
os << "#pragma clang diagnostic ignored \"-W" << diagName << "\"\n";
bodyPrinter();
os << "#pragma clang diagnostic pop\n";
}

void ClangSyntaxPrinter::printIgnoredCxx17ExtensionDiagnosticBlock(
llvm::function_ref<void()> bodyPrinter) {
printIgnoredDiagnosticBlock("c++17-extensions", bodyPrinter);
}
26 changes: 26 additions & 0 deletions lib/PrintAsClang/ClangSyntaxPrinter.h
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,19 @@ class ClangSyntaxPrinter {
bool printNominalTypeOutsideMemberDeclTemplateSpecifiers(
const NominalTypeDecl *typeDecl);

/// Print out additional C++ `static_assert` clauses that
/// are required to emit a generic member definition outside a C++ class that
/// is generated for the given Swift type declaration.
///
/// \returns true if nothing was printed.
///
/// Examples:
/// 1) For Swift's `String` type, it will print nothing.
/// 2) For Swift's `Array<T>` type, it will print
/// `static_assert(swift::isUsableInGenericContext<T_0_0>);\n`
bool printNominalTypeOutsideMemberDeclInnerStaticAssert(
const NominalTypeDecl *typeDecl);

/// Print out the C++ class access qualifier for the given Swift type
/// declaration.
///
Expand Down Expand Up @@ -163,6 +176,11 @@ class ClangSyntaxPrinter {
/// its requirements.
void printGenericSignature(const CanGenericSignature &signature);

/// Print the `static_assert` statements used for legacy type-checking for
/// generics in C++14/C++17 mode.
void
printGenericSignatureInnerStaticAsserts(const CanGenericSignature &signature);

/// Print the C++ template parameters that should be passed for a given
/// generic signature.
void printGenericSignatureParams(const CanGenericSignature &signature);
Expand Down Expand Up @@ -190,6 +208,14 @@ class ClangSyntaxPrinter {
// Print the #define for the given macro.
void printDefine(StringRef macroName);

// Print the ignored Clang diagnostic preprocessor directives around the given
// source.
void printIgnoredDiagnosticBlock(StringRef diagName,
llvm::function_ref<void()> bodyPrinter);

void printIgnoredCxx17ExtensionDiagnosticBlock(
llvm::function_ref<void()> bodyPrinter);

protected:
raw_ostream &os;
};
Expand Down
4 changes: 2 additions & 2 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1379,8 +1379,8 @@ class DeclAndTypePrinter::Implementation
os << " {\n";
funcPrinter.printCxxThunkBody(
FD, funcABI.getSignature(), funcABI.getSymbolName(),
FD->getModuleContext(), resultTy, FD->getParameters(),
funcTy->isThrowing(), funcTy);
/*typeDeclContext=*/nullptr, FD->getModuleContext(), resultTy,
FD->getParameters(), funcTy->isThrowing(), funcTy);
os << "}\n";
}

Expand Down
101 changes: 55 additions & 46 deletions lib/PrintAsClang/PrintClangFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -986,17 +986,17 @@ void DeclAndTypeClangFunctionPrinter::printGenericReturnSequence(
llvm::raw_string_ostream os(resultTyName);
ClangSyntaxPrinter(os).printGenericTypeParamTypeName(gtpt);
}

os << " if constexpr (std::is_base_of<::swift::"
<< cxx_synthesis::getCxxImplNamespaceName() << "::RefCountedClass, "
<< resultTyName << ">::value) {\n";
os << " void *returnValue;\n ";
if (!initializeWithTakeFromValue) {
invocationPrinter(/*additionalParam=*/StringRef(ros.str()));
} else {
os << "returnValue = *reinterpret_cast<void **>("
<< *initializeWithTakeFromValue << ")";
}
ClangSyntaxPrinter(os).printIgnoredCxx17ExtensionDiagnosticBlock([&]() {
os << " if constexpr (std::is_base_of<::swift::"
<< cxx_synthesis::getCxxImplNamespaceName() << "::RefCountedClass, "
<< resultTyName << ">::value) {\n";
os << " void *returnValue;\n ";
if (!initializeWithTakeFromValue) {
invocationPrinter(/*additionalParam=*/StringRef(ros.str()));
} else {
os << "returnValue = *reinterpret_cast<void **>("
<< *initializeWithTakeFromValue << ")";
}
os << ";\n";
os << " return ::swift::" << cxx_synthesis::getCxxImplNamespaceName()
<< "::implClassFor<" << resultTyName
Expand All @@ -1010,41 +1010,49 @@ void DeclAndTypeClangFunctionPrinter::printGenericReturnSequence(
<< ">::type::returnNewValue([&](void * _Nonnull returnValue) {\n";
if (!initializeWithTakeFromValue) {
invocationPrinter(/*additionalParam=*/StringRef("returnValue"));
} else {
os << " return ::swift::" << cxx_synthesis::getCxxImplNamespaceName()
<< "::implClassFor<" << resultTyName
<< ">::type::initializeWithTake(reinterpret_cast<char * "
"_Nonnull>(returnValue), "
<< *initializeWithTakeFromValue << ")";
}
os << ";\n });\n";
os << " } else if constexpr (::swift::"
<< cxx_synthesis::getCxxImplNamespaceName() << "::isSwiftBridgedCxxRecord<"
<< resultTyName << ">) {\n";
if (!initializeWithTakeFromValue) {
ClangTypeHandler::printGenericReturnScaffold(os, resultTyName,
invocationPrinter);
} else {
// FIXME: support taking a C++ record type.
os << "abort();\n";
}
os << " } else {\n";
os << " " << resultTyName << " returnValue;\n";
if (!initializeWithTakeFromValue) {
invocationPrinter(/*additionalParam=*/StringRef(ros.str()));
} else {
os << "memcpy(&returnValue, " << *initializeWithTakeFromValue
<< ", sizeof(returnValue))";
}
os << ";\n return returnValue;\n";
os << " }\n";
} else {
os << " return ::swift::" << cxx_synthesis::getCxxImplNamespaceName()
<< "::implClassFor<" << resultTyName
<< ">::type::initializeWithTake(reinterpret_cast<char * "
"_Nonnull>(returnValue), "
<< *initializeWithTakeFromValue << ")";
}
os << ";\n });\n";
os << " } else if constexpr (::swift::"
<< cxx_synthesis::getCxxImplNamespaceName()
<< "::isSwiftBridgedCxxRecord<" << resultTyName << ">) {\n";
if (!initializeWithTakeFromValue) {
ClangTypeHandler::printGenericReturnScaffold(os, resultTyName,
invocationPrinter);
} else {
// FIXME: support taking a C++ record type.
os << "abort();\n";
}
os << " } else {\n";
os << " " << resultTyName << " returnValue;\n";
if (!initializeWithTakeFromValue) {
invocationPrinter(/*additionalParam=*/StringRef(ros.str()));
} else {
os << "memcpy(&returnValue, " << *initializeWithTakeFromValue
<< ", sizeof(returnValue))";
}
os << ";\n return returnValue;\n";
os << " }\n";
});
}

void DeclAndTypeClangFunctionPrinter::printCxxThunkBody(
const AbstractFunctionDecl *FD, const LoweredFunctionSignature &signature,
StringRef swiftSymbolName, const ModuleDecl *moduleContext, Type resultTy,
const ParameterList *params, bool hasThrows,
const AnyFunctionType *funcType) {
StringRef swiftSymbolName, const NominalTypeDecl *typeDeclContext,
const ModuleDecl *moduleContext, Type resultTy, const ParameterList *params,
bool hasThrows, const AnyFunctionType *funcType) {
if (typeDeclContext)
ClangSyntaxPrinter(os).printNominalTypeOutsideMemberDeclInnerStaticAssert(
typeDeclContext);
if (FD->isGeneric()) {
auto Signature = FD->getGenericSignature().getCanonicalSignature();
ClangSyntaxPrinter(os).printGenericSignatureInnerStaticAsserts(Signature);
}
if (hasThrows) {
os << " void* opaqueError = nullptr;\n";
os << " void* _ctx = nullptr;\n";
Expand Down Expand Up @@ -1280,8 +1288,9 @@ void DeclAndTypeClangFunctionPrinter::printCxxMethod(

os << " {\n";
// FIXME: should it be objTy for resultTy?
printCxxThunkBody(FD, signature, swiftSymbolName, FD->getModuleContext(),
resultTy, FD->getParameters(), FD->hasThrows(),
printCxxThunkBody(FD, signature, swiftSymbolName, typeDeclContext,
FD->getModuleContext(), resultTy, FD->getParameters(),
FD->hasThrows(),
FD->getInterfaceType()->castTo<AnyFunctionType>());
os << " }\n";
}
Expand Down Expand Up @@ -1339,7 +1348,7 @@ void DeclAndTypeClangFunctionPrinter::printCxxPropertyAccessorMethod(
}
os << " {\n";
// FIXME: should it be objTy for resultTy?
printCxxThunkBody(accessor, signature, swiftSymbolName,
printCxxThunkBody(accessor, signature, swiftSymbolName, typeDeclContext,
accessor->getModuleContext(), resultTy,
accessor->getParameters());
os << " }\n";
Expand All @@ -1365,7 +1374,7 @@ void DeclAndTypeClangFunctionPrinter::printCxxSubscriptAccessorMethod(
}
os << " {\n";
// FIXME: should it be objTy for resultTy?
printCxxThunkBody(accessor, signature, swiftSymbolName,
printCxxThunkBody(accessor, signature, swiftSymbolName, typeDeclContext,
accessor->getModuleContext(), resultTy,
accessor->getParameters());
os << " }\n";
Expand Down
1 change: 1 addition & 0 deletions lib/PrintAsClang/PrintClangFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,7 @@ class DeclAndTypeClangFunctionPrinter {
void printCxxThunkBody(const AbstractFunctionDecl *FD,
const LoweredFunctionSignature &signature,
StringRef swiftSymbolName,
const NominalTypeDecl *typeDeclContext,
const ModuleDecl *moduleContext, Type resultTy,
const ParameterList *params, bool hasThrows = false,
const AnyFunctionType *funcType = nullptr);
Expand Down
6 changes: 6 additions & 0 deletions lib/PrintAsClang/PrintClangValueType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,9 @@ void ClangValueTypePrinter::printValueTypeDecl(
ClangSyntaxPrinter(os).printBaseName(typeDecl);
os << " final {\n";
os << "public:\n";
if (genericSignature)
ClangSyntaxPrinter(os).printGenericSignatureInnerStaticAsserts(
*genericSignature);

// Print out the destructor.
os << " inline ~";
Expand Down Expand Up @@ -373,6 +376,9 @@ void ClangValueTypePrinter::printValueTypeDecl(
printCxxImplClassName(os, typeDecl);
os << " {\n";
os << "public:\n";
if (genericSignature)
ClangSyntaxPrinter(os).printGenericSignatureInnerStaticAsserts(
*genericSignature);

os << " static inline char * _Nonnull getOpaquePointer(";
printCxxTypeName(os, typeDecl, moduleContext);
Expand Down
9 changes: 4 additions & 5 deletions lib/PrintAsClang/PrintSwiftToClangCoreScaffold.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -243,10 +243,9 @@ void swift::printSwiftToClangCoreScaffold(SwiftToClangInteropContext &ctx,
});
os << "\n";
// C++ only supports inline variables from C++17.
// FIXME: silence the warning instead?
os << "#if __cplusplus > 201402L\n";
printPrimitiveGenericTypeTraits(os, astContext, typeMapping,
/*isCForwardDefinition=*/false);
os << "#endif\n";
ClangSyntaxPrinter(os).printIgnoredCxx17ExtensionDiagnosticBlock([&]() {
printPrimitiveGenericTypeTraits(os, astContext, typeMapping,
/*isCForwardDefinition=*/false);
});
});
}
Original file line number Diff line number Diff line change
@@ -1 +1 @@
4
5
5 changes: 3 additions & 2 deletions test/Interop/SwiftToCxx/core/swift-impl-defs-in-cxx.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,8 @@
// CHECK-NEXT: } // namespace _impl
// CHECK-EMPTY:
// CHECK-EMPTY:
// CHECK-NEXT: #if __cplusplus > 201402L
// CHECK-NEXT: #pragma clang diagnostic push
// CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions"
// CHECK-NEXT: template<>
// CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<bool> = true;
// CHECK-EMPTY:
Expand Down Expand Up @@ -235,7 +236,7 @@
// CHECK-NEXT: }
// CHECK-NEXT: };
// CHECK-EMPTY:
// CHECK-NEXT: #endif
// CHECK-NEXT: #pragma clang diagnostic pop
// CHECK-EMPTY:
// CHECK-NEXT: } // namespace swift
// CHECK-EMPTY:
Expand Down
Loading