Skip to content

[interop][SwiftToCxx] emit instance property getters for structs #59445

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
Jun 15, 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
92 changes: 77 additions & 15 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,8 @@ class DeclAndTypePrinter::Implementation

SmallVector<const FunctionType *, 4> openFunctionTypes;

std::string outOfLineDefinitions;

ASTContext &getASTContext() const {
return owningPrinter.M.getASTContext();
}
Expand Down Expand Up @@ -211,6 +213,7 @@ class DeclAndTypePrinter::Implementation
template <bool AllowDelayed = false, typename R>
void printMembers(R &&members) {
bool protocolMembersOptional = false;
assert(outOfLineDefinitions.empty());
for (const Decl *member : members) {
auto VD = dyn_cast<ValueDecl>(member);
if (!VD || !shouldInclude(VD) || isa<TypeDecl>(VD))
Expand All @@ -226,6 +229,9 @@ class DeclAndTypePrinter::Implementation
protocolMembersOptional = !protocolMembersOptional;
os << (protocolMembersOptional ? "@optional\n" : "@required\n");
}
// Limit C++ decls for now.
if (outputLang == OutputLanguageMode::Cxx && !isa<VarDecl>(VD))
continue;
ASTVisitor::visit(const_cast<ValueDecl*>(VD));
}
}
Expand Down Expand Up @@ -336,7 +342,10 @@ class DeclAndTypePrinter::Implementation
ClangValueTypePrinter printer(os, owningPrinter.prologueOS,
owningPrinter.typeMapping,
owningPrinter.interopContext);
printer.printValueTypeDecl(SD);
printer.printValueTypeDecl(
SD, /*bodyPrinter=*/[&]() { printMembers(SD->getMembers()); });
os << outOfLineDefinitions;
outOfLineDefinitions.clear();
}

void visitExtensionDecl(ExtensionDecl *ED) {
Expand Down Expand Up @@ -514,6 +523,45 @@ class DeclAndTypePrinter::Implementation
bool isClassMethod,
bool isNSUIntegerSubscript = false) {
printDocumentationComment(AFD);

Optional<ForeignAsyncConvention> asyncConvention =
AFD->getForeignAsyncConvention();
Optional<ForeignErrorConvention> errorConvention =
AFD->getForeignErrorConvention();
Type rawMethodTy = AFD->getMethodInterfaceType();
auto methodTy = rawMethodTy->castTo<FunctionType>();
auto resultTy =
getForeignResultType(AFD, methodTy, asyncConvention, errorConvention);

if (outputLang == OutputLanguageMode::Cxx) {
auto *typeDeclContext = cast<NominalTypeDecl>(AFD->getParent());

std::string cFuncDecl;
llvm::raw_string_ostream cFuncPrologueOS(cFuncDecl);
auto funcABI = Implementation(cFuncPrologueOS, owningPrinter, outputLang)
.printSwiftABIFunctionSignatureAsCxxFunction(
AFD, methodTy,
/*selfTypeDeclContext=*/typeDeclContext);
owningPrinter.prologueOS << cFuncPrologueOS.str();

DeclAndTypeClangFunctionPrinter declPrinter(os, owningPrinter.prologueOS,
owningPrinter.typeMapping,
owningPrinter.interopContext);
declPrinter.printCxxPropertyAccessorMethod(
typeDeclContext, AFD, funcABI.getSymbolName(), resultTy,
/*isDefinition=*/false);

llvm::raw_string_ostream defOS(outOfLineDefinitions);
DeclAndTypeClangFunctionPrinter defPrinter(
defOS, owningPrinter.prologueOS, owningPrinter.typeMapping,
owningPrinter.interopContext);
defPrinter.printCxxPropertyAccessorMethod(
typeDeclContext, AFD, funcABI.getSymbolName(), resultTy,
/*isDefinition=*/true);

return;
}

if (isClassMethod)
os << "+ (";
else
Expand All @@ -527,15 +575,6 @@ class DeclAndTypePrinter::Implementation
}
}

Optional<ForeignAsyncConvention> asyncConvention
= AFD->getForeignAsyncConvention();
Optional<ForeignErrorConvention> errorConvention
= AFD->getForeignErrorConvention();
Type rawMethodTy = AFD->getMethodInterfaceType();
auto methodTy = rawMethodTy->castTo<FunctionType>();
auto resultTy = getForeignResultType(
AFD, methodTy, asyncConvention, errorConvention);

// Constructors and methods returning DynamicSelf return
// instancetype.
if (isa<ConstructorDecl>(AFD) ||
Expand Down Expand Up @@ -796,7 +835,8 @@ class DeclAndTypePrinter::Implementation
}

struct FuncionSwiftABIInformation {
FuncionSwiftABIInformation(FuncDecl *FD, Mangle::ASTMangler &mangler) {
FuncionSwiftABIInformation(AbstractFunctionDecl *FD,
Mangle::ASTMangler &mangler) {
isCDecl = FD->getAttrs().hasAttribute<CDeclAttr>();
if (!isCDecl) {
auto mangledName = mangler.mangleAnyDecl(FD, /*prefix=*/true);
Expand All @@ -818,8 +858,9 @@ class DeclAndTypePrinter::Implementation
};

// Print out the extern C Swift ABI function signature.
FuncionSwiftABIInformation
printSwiftABIFunctionSignatureAsCxxFunction(FuncDecl *FD) {
FuncionSwiftABIInformation printSwiftABIFunctionSignatureAsCxxFunction(
AbstractFunctionDecl *FD, Optional<FunctionType *> givenFuncType = None,
Optional<NominalTypeDecl *> selfTypeDeclContext = None) {
assert(outputLang == OutputLanguageMode::Cxx);
Optional<ForeignAsyncConvention> asyncConvention =
FD->getForeignAsyncConvention();
Expand All @@ -828,7 +869,9 @@ class DeclAndTypePrinter::Implementation
assert(!FD->getGenericSignature() &&
"top-level generic functions not supported here");
// FIXME (Alex): Make type adjustments for C++.
auto funcTy = FD->getInterfaceType()->castTo<FunctionType>();
auto funcTy = givenFuncType
? *givenFuncType
: FD->getInterfaceType()->castTo<FunctionType>();
auto resultTy =
getForeignResultType(FD, funcTy, asyncConvention, errorConvention);

Expand All @@ -840,9 +883,17 @@ class DeclAndTypePrinter::Implementation
DeclAndTypeClangFunctionPrinter funcPrinter(os, owningPrinter.prologueOS,
owningPrinter.typeMapping,
owningPrinter.interopContext);
llvm::SmallVector<DeclAndTypeClangFunctionPrinter::AdditionalParam, 1>
additionalParams;
if (selfTypeDeclContext) {
additionalParams.push_back(
{DeclAndTypeClangFunctionPrinter::AdditionalParam::Role::Self,
(*selfTypeDeclContext)->getDeclaredType()});
}
funcPrinter.printFunctionSignature(
FD, funcABI.getSymbolName(), resultTy,
DeclAndTypeClangFunctionPrinter::FunctionSignatureKind::CFunctionProto);
DeclAndTypeClangFunctionPrinter::FunctionSignatureKind::CFunctionProto,
additionalParams);
// Swift functions can't throw exceptions, we can only
// throw them from C++ when emitting C++ inline thunks for the Swift
// functions.
Expand Down Expand Up @@ -1186,6 +1237,17 @@ class DeclAndTypePrinter::Implementation
assert(VD->getDeclContext()->isTypeContext() &&
"cannot handle global variables right now");

if (outputLang == OutputLanguageMode::Cxx) {
// FIXME: Documentation.
// FIXME: availability.
// FIXME: support static properties.
if (VD->isStatic())
return;
auto *getter = VD->getOpaqueAccessor(AccessorKind::Get);
printAbstractFunctionAsMethod(getter, /*isStatic=*/false);
return;
}

printDocumentationComment(VD);

if (VD->isStatic()) {
Expand Down
3 changes: 2 additions & 1 deletion lib/PrintAsClang/ModuleContentsWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -662,8 +662,9 @@ void swift::printModuleContentsAsCxx(
std::string modulePrologueBuf;
llvm::raw_string_ostream prologueOS{modulePrologueBuf};

// FIXME: Use getRequiredAccess once @expose is supported.
ModuleWriter writer(moduleOS, prologueOS, imports, M, interopContext,
getRequiredAccess(M), OutputLanguageMode::Cxx);
AccessLevel::Public, OutputLanguageMode::Cxx);
writer.write();

os << "#ifndef SWIFT_PRINTED_CORE\n";
Expand Down
1 change: 1 addition & 0 deletions lib/PrintAsClang/PrintAsClang.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -317,6 +317,7 @@ static void writePrologue(raw_ostream &out, ASTContext &ctx,
};
emitMacro("SWIFT_CALL", "__attribute__((swiftcall))");
emitMacro("SWIFT_INDIRECT_RESULT", "__attribute__((swift_indirect_result))");
emitMacro("SWIFT_CONTEXT", "__attribute__((swift_context))");
// SWIFT_NOEXCEPT applies 'noexcept' in C++ mode only.
emitCxxConditional(
out, [&] { emitMacro("SWIFT_NOEXCEPT", "noexcept"); },
Expand Down
Loading