Skip to content

[interop][SwiftToCxx] add support for constructing generic enum cases… #61913

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 1 commit into from
Nov 4, 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
2 changes: 1 addition & 1 deletion docs/CppInteroperability/CppInteroperabilityStatus.md
Original file line number Diff line number Diff line change
Expand Up @@ -218,4 +218,4 @@ This status table describes which of the following Swift standard library APIs h
|--------------------------------|----------------------------------------------------------|
| `String` | Can be used as a type in C++. APIs in extensions are not exposed to C++. Conversion between `std.string` is not yet supported |
| `Array<T>` | Can be used as a type in C++. Ranged for loops are supported. Limited set of APIs in some extensions are exposed to C++. |
| `Optional<T>` | Can be used as a type in C++. `get` extracts the optional value and it's also implicitly castable to `bool`. Can't be constructed from C++ yet. |
| `Optional<T>` | Can be used as a type in C++. Can be constructed. `get` extracts the optional value and it's also implicitly castable to `bool`. |
177 changes: 113 additions & 64 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -466,6 +466,7 @@ class DeclAndTypePrinter::Implementation

clangFuncPrinter.printCustomCxxFunction(
{paramType},
/*NeedsReturnTypes=*/true,
[&](auto &types) {
// Printing function name and return type
os << " inline " << types[paramType] << " get" << name;
Expand Down Expand Up @@ -535,13 +536,13 @@ class DeclAndTypePrinter::Implementation
outOfLineOS << " });\n ";
}
},
ED->getModuleContext(), outOfLineOS);
ED, ED->getModuleContext(), outOfLineOS);
};

auto printStruct = [&](StringRef caseName, EnumElementDecl *elementDecl,
Optional<IRABIDetailsProvider::EnumElementInfo>
elementInfo) {
os << " inline const static struct { "
os << " inline const static struct _impl_" << caseName << " { "
<< "// impl struct for case " << caseName << '\n';
os << " inline constexpr operator cases() const {\n";
os << " return cases::";
Expand All @@ -552,67 +553,112 @@ class DeclAndTypePrinter::Implementation
if (elementDecl != nullptr) {
assert(elementInfo.hasValue());

Type paramType, objectType;
NominalTypeDecl *objectTypeDecl = nullptr;
OptionalTypeKind optKind;
Type paramType;

// TODO: support tuple type
if (elementDecl->hasAssociatedValues() &&
elementDecl->getParameterList()->size() == 1) {
paramType = elementDecl->getParameterList()->front()->getType();
std::tie(objectType, optKind) = getObjectTypeAndOptionality(
paramType->getNominalOrBoundGenericNominal(), paramType);
objectTypeDecl = objectType->getNominalOrBoundGenericNominal();
paramType =
elementDecl->getParameterList()->front()->getInterfaceType();
}

SmallVector<Type> neededTypes;
if (paramType) {
neededTypes.push_back(paramType);
}

// FIXME: support generic constructor.
if (!ED->isGeneric())
clangFuncPrinter.printCustomCxxFunction(
neededTypes,
[&](auto &types) {
// Printing function name and return type
os << " inline ";
syntaxPrinter.printBaseName(elementDecl->getParentEnum());
os << " operator()";

outOfLineOS << " inline ";
outOfLineSyntaxPrinter.printBaseName(
elementDecl->getParentEnum());
outOfLineOS << ' ';
outOfLineSyntaxPrinter.printBaseName(
elementDecl->getParentEnum());
outOfLineOS << "::_impl_" << elementDecl->getNameStr()
<< "::operator()";
},
[&](auto &types) {
// Printing parameters
if (!paramType) {
return;
}
assert(objectTypeDecl != nullptr);
if (owningPrinter.typeMapping.getKnownCxxTypeInfo(
objectTypeDecl)) {
os << types[paramType] << " val";
outOfLineOS << types[paramType] << " val";
clangFuncPrinter.printCustomCxxFunction(
neededTypes,
/*NeedsReturnTypes=*/false,
[&](auto &types) {
const auto *ED = elementDecl->getParentEnum();
// Printing function name and return type
os << " inline ";
syntaxPrinter.printNominalTypeReference(ED,
ED->getModuleContext());
os << " operator()";

outOfLineSyntaxPrinter
.printNominalTypeOutsideMemberDeclTemplateSpecifiers(ED);
outOfLineOS << " inline ";
outOfLineSyntaxPrinter.printNominalTypeReference(
ED, ED->getModuleContext());
outOfLineOS << ' ';
outOfLineSyntaxPrinter.printNominalTypeQualifier(
ED, /*moduleContext=*/ED->getModuleContext());
outOfLineOS << "_impl_" << caseName << "::operator()";
},
[&](auto &types) {
// Printing parameters
if (!paramType) {
return;
}
os << types[paramType] << " val";
outOfLineOS << types[paramType] << " val";
},
true,
[&](auto &types) {
auto *ED = elementDecl->getParentEnum();
// Printing function body
outOfLineOS << " auto result = ";
outOfLineSyntaxPrinter.printNominalTypeQualifier(
ED, ED->getModuleContext());
outOfLineOS << "_make();\n";
if (paramType) {
if (paramType->getAs<GenericTypeParamType>()) {
auto type = types[paramType];
ClangSyntaxPrinter(outOfLineOS)
.printIgnoredCxx17ExtensionDiagnosticBlock([&]() {
// FIXME: handle C++ types.
outOfLineOS << "if constexpr (std::is_base_of<::swift::"
<< cxx_synthesis::getCxxImplNamespaceName()
<< "::RefCountedClass, " << type
<< ">::value) {\n";
outOfLineOS << " void *ptr = ::swift::"
<< cxx_synthesis::getCxxImplNamespaceName()
<< "::_impl_RefCountedClass::"
"copyOpaquePointer(val);\n";
outOfLineOS
<< " memcpy(result._getOpaquePointer(), &ptr, "
"sizeof(ptr));\n";
outOfLineOS << "} else if constexpr (::swift::"
<< cxx_synthesis::getCxxImplNamespaceName()
<< "::isValueType<" << type << ">) {\n";

outOfLineOS << " alignas(" << type;
outOfLineOS << ") unsigned char buffer[sizeof(" << type;
outOfLineOS << ")];\n";
outOfLineOS << " auto *valCopy = new(buffer) "
<< type;
outOfLineOS << "(val);\n";
outOfLineOS << " ";
outOfLineOS << cxx_synthesis::getCxxSwiftNamespaceName()
<< "::";
outOfLineOS << cxx_synthesis::getCxxImplNamespaceName();
outOfLineOS << "::implClassFor<" << type;
outOfLineOS << ">::type::initializeWithTake(result._"
"getOpaquePointer(), ";
outOfLineOS << cxx_synthesis::getCxxSwiftNamespaceName()
<< "::";
outOfLineOS << cxx_synthesis::getCxxImplNamespaceName();
outOfLineOS << "::implClassFor<" << type;
outOfLineOS << ">::type::getOpaquePointer(*valCopy)";
outOfLineOS << ");\n";
outOfLineOS << "} else {\n";
outOfLineOS
<< " memcpy(result._getOpaquePointer(), &val, "
"sizeof(val));\n";
outOfLineOS << "}\n";
});
} else {
os << "const " << types[paramType] << " &val";
outOfLineOS << "const " << types[paramType] << " &val";
}
},
true,
[&](auto &types) {
// Printing function body
outOfLineOS << " auto result = ";
outOfLineSyntaxPrinter.printBaseName(
elementDecl->getParentEnum());
outOfLineOS << "::_make();\n";

if (paramType) {

OptionalTypeKind optKind;
Type objectType;
std::tie(objectType, optKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(
ED, paramType);
auto objectTypeDecl =
objectType->getNominalOrBoundGenericNominal();
assert(objectTypeDecl != nullptr);

if (owningPrinter.typeMapping.getKnownCxxTypeInfo(
Expand All @@ -621,6 +667,8 @@ class DeclAndTypePrinter::Implementation
<< " memcpy(result._getOpaquePointer(), &val, "
"sizeof(val));\n";
} else {
objectTypeDecl =
paramType->getNominalOrBoundGenericNominal();
outOfLineOS << " alignas(";
outOfLineSyntaxPrinter
.printModuleNamespaceQualifiersIfNeeded(
Expand Down Expand Up @@ -666,19 +714,20 @@ class DeclAndTypePrinter::Implementation
outOfLineOS << ");\n";
}
}

outOfLineOS << " result._destructiveInjectEnumTag(";
if (ED->isResilient()) {
outOfLineOS << cxx_synthesis::getCxxImplNamespaceName()
<< "::" << elementInfo->globalVariableName;
} else {
outOfLineOS << elementInfo->tag;
}
outOfLineOS << ");\n";
outOfLineOS << " return result;\n";
outOfLineOS << " ";
},
ED->getModuleContext(), outOfLineOS);
}

outOfLineOS << " result._destructiveInjectEnumTag(";
if (ED->isResilient()) {
outOfLineOS << cxx_synthesis::getCxxImplNamespaceName()
<< "::" << elementInfo->globalVariableName;
} else {
outOfLineOS << elementInfo->tag;
}
outOfLineOS << ");\n";
outOfLineOS << " return result;\n";
outOfLineOS << " ";
},
ED, ED->getModuleContext(), outOfLineOS);
}
os << " } ";
syntaxPrinter.printIdentifier(caseName);
Expand Down
36 changes: 24 additions & 12 deletions lib/PrintAsClang/PrintClangFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1394,29 +1394,41 @@ bool DeclAndTypeClangFunctionPrinter::hasKnownOptionalNullableCxxMapping(
}

void DeclAndTypeClangFunctionPrinter::printCustomCxxFunction(
const SmallVector<Type> &neededTypes, PrinterTy retTypeAndNamePrinter,
PrinterTy paramPrinter, bool isConstFunc, PrinterTy bodyPrinter,
ModuleDecl *emittedModule, raw_ostream &outOfLineOS) {
const SmallVector<Type> &neededTypes, bool NeedsReturnTypes,
PrinterTy retTypeAndNamePrinter, PrinterTy paramPrinter, bool isConstFunc,
PrinterTy bodyPrinter, ValueDecl *valueDecl, ModuleDecl *emittedModule,
raw_ostream &outOfLineOS) {
llvm::MapVector<Type, std::string> types;
llvm::MapVector<Type, std::string> typeRefs;

for (auto &type : neededTypes) {
std::string typeStr;
llvm::raw_string_ostream typeOS(typeStr);
OptionalTypeKind optKind;
Type objectType;
std::tie(objectType, optKind) =
DeclAndTypePrinter::getObjectTypeAndOptionality(
type->getNominalOrBoundGenericNominal(), type);
DeclAndTypePrinter::getObjectTypeAndOptionality(valueDecl, type);

// Use FunctionSignatureTypeUse::ReturnType to avoid printing extra const or
// references
CFunctionSignatureTypePrinter typePrinter(
typeOS, cPrologueOS, typeMapping, OutputLanguageMode::Cxx,
interopContext, CFunctionSignatureTypePrinterModifierDelegate(),
emittedModule, declPrinter, FunctionSignatureTypeUse::ReturnType);
typePrinter.visit(objectType, optKind, /* isInOutParam */ false);

types.insert({type, typeStr});
emittedModule, declPrinter,
NeedsReturnTypes ? FunctionSignatureTypeUse::ReturnType
: FunctionSignatureTypeUse::ParamType);
auto support =
typePrinter.visit(objectType, optKind, /* isInOutParam */ false);
(void)support;
assert(!support.isUnsupported());
types.insert({type, typeOS.str()});

std::string typeRefStr;
llvm::raw_string_ostream typeRefOS(typeRefStr);
CFunctionSignatureTypePrinter typeRefPrinter(
typeRefOS, cPrologueOS, typeMapping, OutputLanguageMode::Cxx,
interopContext, CFunctionSignatureTypePrinterModifierDelegate(),
emittedModule, declPrinter, FunctionSignatureTypeUse::TypeReference);
typeRefPrinter.visit(objectType, optKind, /* isInOutParam */ false);
typeRefs.insert({type, typeRefOS.str()});
}

retTypeAndNamePrinter(types);
Expand All @@ -1430,6 +1442,6 @@ void DeclAndTypeClangFunctionPrinter::printCustomCxxFunction(
outOfLineOS << " const";
}
outOfLineOS << " {\n";
bodyPrinter(types);
bodyPrinter(typeRefs);
outOfLineOS << "}\n";
}
4 changes: 3 additions & 1 deletion lib/PrintAsClang/PrintClangFunction.h
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,11 @@ class DeclAndTypeClangFunctionPrinter {

/// Print generated C++ helper function
void printCustomCxxFunction(const SmallVector<Type> &neededTypes,
bool NeedsReturnTypes,
PrinterTy retTypeAndNamePrinter,
PrinterTy paramPrinter, bool isConstFunc,
PrinterTy bodyPrinter, ModuleDecl *emittedModule,
PrinterTy bodyPrinter, ValueDecl *valueDecl,
ModuleDecl *emittedModule,
raw_ostream &outOfLineOS);

private:
Expand Down
7 changes: 0 additions & 7 deletions lib/PrintAsClang/PrintClangValueType.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -342,13 +342,6 @@ void ClangValueTypePrinter::printValueTypeDecl(
os << " return enumVWTable->getEnumTag(_getOpaquePointer(), "
"metadata._0);\n";
os << " }\n";

for (const auto &pair : interopContext.getIrABIDetails().getEnumTagMapping(
cast<EnumDecl>(typeDecl))) {
os << " using _impl_" << pair.first->getNameStr() << " = decltype(";
ClangSyntaxPrinter(os).printIdentifier(pair.first->getNameStr());
os << ");\n";
}
}
// Print out the storage for the value type.
os << " ";
Expand Down
5 changes: 5 additions & 0 deletions lib/PrintAsClang/_SwiftCxxInteroperability.h
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ class _impl_RefCountedClass {
static inline void *_Nonnull &getOpaquePointerRef(RefCountedClass &object) {
return object._opaquePointer;
}
static inline void *_Nonnull copyOpaquePointer(
const RefCountedClass &object) {
swift_retain(object._opaquePointer);
return object._opaquePointer;
}
};

} // namespace _impl
Expand Down
4 changes: 2 additions & 2 deletions test/Interop/SwiftToCxx/enums/resilient-enum-in-cxx.swift
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ public enum Empty {
// CHECK: enum class cases {
// CHECK-NEXT: unknownDefault
// CHECK-NEXT: };
// CHECK: inline const static struct { // impl struct for case unknownDefault
// CHECK: inline const static struct _impl_unknownDefault { // impl struct for case unknownDefault
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::unknownDefault;
// CHECK-NEXT: }
Expand All @@ -70,7 +70,7 @@ public enum Empty {
// NEW_CASE-NEXT: b,
// CHECK-NEXT: unknownDefault
// CHECK-NEXT: }
// CHECK: inline const static struct { // impl struct for case unknownDefault
// CHECK: inline const static struct _impl_unknownDefault { // impl struct for case unknownDefault
// CHECK-NEXT: inline constexpr operator cases() const {
// CHECK-NEXT: return cases::unknownDefault;
// CHECK-NEXT: }
Expand Down
Loading