Skip to content

[interop][SwiftToCxx] add @_expose(Cxx) attribute suppport #60715

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
Aug 24, 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
16 changes: 16 additions & 0 deletions docs/ReferenceGuides/UnderscoredAttributes.md
Original file line number Diff line number Diff line change
Expand Up @@ -358,6 +358,22 @@ func g() {
}
```

## `@_expose(<language>)`

Indicates that a particular declaration should be included
in the emitted specified foreign language binding.

When applied to a nominal type declaration, all of the
public declarations inside this type become exposed as well.

### `_expose(Cxx[, <"cxxName">])`

Indicates that a particular declaration should be included
in the generated C++ binding header.

The optional "cxxName" string will be used as the name of
the generated C++ declaration.

## `@_fixed_layout`

Same as `@frozen` but also works for classes.
Expand Down
6 changes: 6 additions & 0 deletions include/swift/AST/Attr.def
Original file line number Diff line number Diff line change
Expand Up @@ -757,6 +757,12 @@ SIMPLE_DECL_ATTR(_alwaysEmitConformanceMetadata, AlwaysEmitConformanceMetadata,
OnProtocol | UserInaccessible | ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
132)

DECL_ATTR(_expose, Expose,
OnFunc | OnNominalType | OnVar |
LongAttribute | UserInaccessible |
ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
133)

// If you're adding a new underscored attribute here, please document it in
// docs/ReferenceGuides/UnderscoredAttributes.md.

Expand Down
17 changes: 17 additions & 0 deletions include/swift/AST/Attr.h
Original file line number Diff line number Diff line change
Expand Up @@ -2226,6 +2226,23 @@ class BackDeployAttr: public DeclAttribute {
}
};

/// Defines the `@_expose` attribute, used to expose declarations in the
/// header used by C/C++ to interoperate with Swift.
class ExposeAttr : public DeclAttribute {
public:
ExposeAttr(StringRef Name, SourceLoc AtLoc, SourceRange Range, bool Implicit)
: DeclAttribute(DAK_Expose, AtLoc, Range, Implicit), Name(Name) {}

ExposeAttr(StringRef Name, bool Implicit)
: ExposeAttr(Name, SourceLoc(), SourceRange(), Implicit) {}

/// The exposed declaration name.
const StringRef Name;

static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_Expose;
}
};

/// Attributes that may be applied to declarations.
class DeclAttributes {
Expand Down
5 changes: 5 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -1481,6 +1481,11 @@ ERROR(cdecl_empty_name,none,
ERROR(cdecl_throws,none,
"raising errors from @_cdecl functions is not supported", ())

ERROR(expose_only_non_other_attr,none,
"@_expose attribute cannot be applied to an '%0' declaration", (StringRef))
ERROR(expose_inside_unexposed_decl,none,
"@_expose attribute cannot be applied inside of unexposed declaration %0", (DeclName))

ERROR(attr_methods_only,none,
"only methods can be declared %0", (DeclAttribute))
ERROR(attr_decl_async,none,
Expand Down
6 changes: 6 additions & 0 deletions include/swift/AST/SwiftNameTranslation.h
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,12 @@ namespace objc_translation {

namespace cxx_translation {

using objc_translation::CustomNamesOnly_t;

StringRef
getNameForCxx(const ValueDecl *VD,
CustomNamesOnly_t customNamesOnly = objc_translation::Normal);

/// Returns true if the given value decl D is visible to C++ of its
/// own accord (i.e. without considering its context)
bool isVisibleToCxx(const ValueDecl *VD, AccessLevel minRequiredAccess,
Expand Down
10 changes: 10 additions & 0 deletions lib/AST/Attr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1046,6 +1046,14 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
Printer << "@_cdecl(\"" << cast<CDeclAttr>(this)->Name << "\")";
break;

case DAK_Expose:
Printer.printAttrName("@_expose");
Printer << "(Cxx";
if (!cast<ExposeAttr>(this)->Name.empty())
Printer << ", \"" << cast<ExposeAttr>(this)->Name << "\"";
Printer << ")";
break;

case DAK_ObjC: {
Printer.printAttrName("@objc");
llvm::SmallString<32> scratch;
Expand Down Expand Up @@ -1440,6 +1448,8 @@ StringRef DeclAttribute::getAttrName() const {
return "_unavailableFromAsync";
case DAK_BackDeploy:
return "_backDeploy";
case DAK_Expose:
return "_expose";
}
llvm_unreachable("bad DeclAttrKind");
}
Expand Down
14 changes: 14 additions & 0 deletions lib/AST/SwiftNameTranslation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,20 @@ isVisibleToObjC(const ValueDecl *VD, AccessLevel minRequiredAccess,
return false;
}

StringRef
swift::cxx_translation::getNameForCxx(const ValueDecl *VD,
CustomNamesOnly_t customNamesOnly) {
if (const auto *Expose = VD->getAttrs().getAttribute<ExposeAttr>()) {
if (!Expose->Name.empty())
return Expose->Name;
}

if (customNamesOnly)
return StringRef();

return VD->getBaseIdentifier().str();
}

bool swift::cxx_translation::isVisibleToCxx(const ValueDecl *VD,
AccessLevel minRequiredAccess,
bool checkParent) {
Expand Down
40 changes: 31 additions & 9 deletions lib/Parse/ParseDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2376,27 +2376,45 @@ bool Parser::parseNewDeclAttribute(DeclAttributes &Attributes, SourceLoc AtLoc,
}

case DAK_CDecl:
case DAK_Expose:
case DAK_SILGenName: {
if (!consumeIf(tok::l_paren)) {
diagnose(Loc, diag::attr_expected_lparen, AttrName,
DeclAttribute::isDeclModifier(DK));
return false;
}

if (Tok.isNot(tok::string_literal)) {
diagnose(Loc, diag::attr_expected_string_literal, AttrName);
return false;
bool ParseSymbolName = true;
if (DK == DAK_Expose) {
if (Tok.isNot(tok::identifier) || Tok.getText() != "Cxx") {
diagnose(Tok.getLoc(), diag::attr_expected_option_such_as, AttrName,
"Cxx");
if (Tok.isNot(tok::identifier))
return false;
DiscardAttribute = true;
}
consumeToken(tok::identifier);
ParseSymbolName = consumeIf(tok::comma);
}

Optional<StringRef> AsmName = getStringLiteralIfNotInterpolated(
Loc, ("'" + AttrName + "'").str());
Optional<StringRef> AsmName;
if (ParseSymbolName) {
if (Tok.isNot(tok::string_literal)) {
diagnose(Loc, diag::attr_expected_string_literal, AttrName);
return false;
}

consumeToken(tok::string_literal);
AsmName =
getStringLiteralIfNotInterpolated(Loc, ("'" + AttrName + "'").str());

if (AsmName.hasValue())
consumeToken(tok::string_literal);

if (AsmName.hasValue())
AttrRange = SourceRange(Loc, Tok.getRange().getStart());
else
DiscardAttribute = true;
} else
AttrRange = SourceRange(Loc, Tok.getRange().getStart());
else
DiscardAttribute = true;

if (!consumeIf(tok::r_paren)) {
diagnose(Loc, diag::attr_expected_rparen, AttrName,
Expand All @@ -2419,6 +2437,10 @@ bool Parser::parseNewDeclAttribute(DeclAttributes &Attributes, SourceLoc AtLoc,
else if (DK == DAK_CDecl)
Attributes.add(new (Context) CDeclAttr(AsmName.getValue(), AtLoc,
AttrRange, /*Implicit=*/false));
else if (DK == DAK_Expose)
Attributes.add(new (Context) ExposeAttr(
AsmName ? AsmName.getValue() : StringRef(""), AtLoc, AttrRange,
/*Implicit=*/false));
else
llvm_unreachable("out of sync with switch");
}
Expand Down
3 changes: 2 additions & 1 deletion lib/PrintAsClang/ClangSyntaxPrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
#include "swift/ABI/MetadataValues.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Module.h"
#include "swift/AST/SwiftNameTranslation.h"

using namespace swift;
using namespace cxx_synthesis;
Expand Down Expand Up @@ -52,7 +53,7 @@ void ClangSyntaxPrinter::printIdentifier(StringRef name) {

void ClangSyntaxPrinter::printBaseName(const ValueDecl *decl) {
assert(decl->getName().isSimpleName());
printIdentifier(decl->getBaseIdentifier().str());
printIdentifier(cxx_translation::getNameForCxx(decl));
}

void ClangSyntaxPrinter::printModuleNameCPrefix(const ModuleDecl &mod) {
Expand Down
12 changes: 10 additions & 2 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1203,7 +1203,7 @@ class DeclAndTypePrinter::Implementation
DeclAndTypeClangFunctionPrinter::FunctionSignatureModifiers modifiers;
modifiers.isInline = true;
funcPrinter.printFunctionSignature(
FD, FD->getName().getBaseIdentifier().get(), resultTy,
FD, cxx_translation::getNameForCxx(FD), resultTy,
DeclAndTypeClangFunctionPrinter::FunctionSignatureKind::CxxInlineThunk,
{}, modifiers);
// FIXME: Support throwing exceptions for Swift errors.
Expand Down Expand Up @@ -2393,8 +2393,16 @@ static bool isAsyncAlternativeOfOtherDecl(const ValueDecl *VD) {
return false;
}

static bool hasExposeAttr(const ValueDecl *VD) {
if (VD->getAttrs().hasAttribute<ExposeAttr>())
return true;
if (const auto *NMT = dyn_cast<NominalTypeDecl>(VD->getDeclContext()))
return hasExposeAttr(NMT);
return false;
}

bool DeclAndTypePrinter::shouldInclude(const ValueDecl *VD) {
return !VD->isInvalid() &&
return !VD->isInvalid() && (!requiresExposedAttribute || hasExposeAttr(VD)) &&
(outputLang == OutputLanguageMode::Cxx
? cxx_translation::isVisibleToCxx(VD, minRequiredAccess)
: isVisibleToObjC(VD, minRequiredAccess)) &&
Expand Down
8 changes: 6 additions & 2 deletions lib/PrintAsClang/DeclAndTypePrinter.h
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ class DeclAndTypePrinter {
PrimitiveTypeMapping &typeMapping;
SwiftToClangInteropContext &interopContext;
AccessLevel minRequiredAccess;
bool requiresExposedAttribute;
OutputLanguageMode outputLang;

/// The name 'CFTypeRef'.
Expand All @@ -62,11 +63,14 @@ class DeclAndTypePrinter {
DelayedMemberSet &delayed,
PrimitiveTypeMapping &typeMapping,
SwiftToClangInteropContext &interopContext,
AccessLevel access, OutputLanguageMode outputLang)
AccessLevel access, bool requiresExposedAttribute,
OutputLanguageMode outputLang)
: M(mod), os(out), prologueOS(prologueOS),
outOfLineDefinitionsOS(outOfLineDefinitionsOS), delayedMembers(delayed),
typeMapping(typeMapping), interopContext(interopContext),
minRequiredAccess(access), outputLang(outputLang) {}
minRequiredAccess(access),
requiresExposedAttribute(requiresExposedAttribute),
outputLang(outputLang) {}

/// Returns true if \p VD should be included in a compatibility header for
/// the options the printer was constructed with.
Expand Down
13 changes: 8 additions & 5 deletions lib/PrintAsClang/ModuleContentsWriter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -136,11 +136,12 @@ class ModuleWriter {
ModuleWriter(raw_ostream &os, raw_ostream &prologueOS,
llvm::SmallPtrSetImpl<ImportModuleTy> &imports, ModuleDecl &mod,
SwiftToClangInteropContext &interopContext, AccessLevel access,
OutputLanguageMode outputLang)
bool requiresExposedAttribute, OutputLanguageMode outputLang)
: os(os), imports(imports), M(mod),
outOfLineDefinitionsOS(outOfLineDefinitions),
printer(M, os, prologueOS, outOfLineDefinitionsOS, delayedMembers,
typeMapping, interopContext, access, outputLang),
typeMapping, interopContext, access, requiresExposedAttribute,
outputLang),
outputLangMode(outputLang) {}

PrimitiveTypeMapping &getTypeMapping() { return typeMapping; }
Expand Down Expand Up @@ -672,21 +673,23 @@ void swift::printModuleContentsAsObjC(
ModuleDecl &M, SwiftToClangInteropContext &interopContext) {
llvm::raw_null_ostream prologueOS;
ModuleWriter(os, prologueOS, imports, M, interopContext, getRequiredAccess(M),
OutputLanguageMode::ObjC)
/*requiresExposedAttribute=*/false, OutputLanguageMode::ObjC)
.write();
}

void swift::printModuleContentsAsCxx(
raw_ostream &os, llvm::SmallPtrSetImpl<ImportModuleTy> &imports,
ModuleDecl &M, SwiftToClangInteropContext &interopContext) {
ModuleDecl &M, SwiftToClangInteropContext &interopContext,
bool requiresExposedAttribute) {
std::string moduleContentsBuf;
llvm::raw_string_ostream moduleOS{moduleContentsBuf};
std::string modulePrologueBuf;
llvm::raw_string_ostream prologueOS{modulePrologueBuf};

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

os << "#ifndef SWIFT_PRINTED_CORE\n";
Expand Down
4 changes: 3 additions & 1 deletion lib/PrintAsClang/ModuleContentsWriter.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ namespace clang {
}

namespace swift {
class Decl;
class ModuleDecl;
class SwiftToClangInteropContext;

Expand All @@ -40,7 +41,8 @@ void printModuleContentsAsObjC(raw_ostream &os,
void printModuleContentsAsCxx(raw_ostream &os,
llvm::SmallPtrSetImpl<ImportModuleTy> &imports,
ModuleDecl &M,
SwiftToClangInteropContext &interopContext);
SwiftToClangInteropContext &interopContext,
bool requiresExposedAttribute);

} // end namespace swift

Expand Down
13 changes: 9 additions & 4 deletions lib/PrintAsClang/PrintAsClang.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -491,11 +491,13 @@ static std::string computeMacroGuard(const ModuleDecl *M) {

static std::string
getModuleContentsCxxString(ModuleDecl &M,
SwiftToClangInteropContext &interopContext) {
SwiftToClangInteropContext &interopContext,
bool requiresExposedAttribute) {
SmallPtrSet<ImportModuleTy, 8> imports;
std::string moduleContentsBuf;
llvm::raw_string_ostream moduleContents{moduleContentsBuf};
printModuleContentsAsCxx(moduleContents, imports, M, interopContext);
printModuleContentsAsCxx(moduleContents, imports, M, interopContext,
requiresExposedAttribute);
return moduleContents.str();
}

Expand All @@ -518,8 +520,11 @@ bool swift::printAsClangHeader(raw_ostream &os, ModuleDecl *M,
emitObjCConditional(os, [&] { os << objcModuleContents.str(); });
emitCxxConditional(os, [&] {
// FIXME: Expose Swift with @expose by default.
if (ExposePublicDeclsInClangHeader) {
os << getModuleContentsCxxString(*M, interopContext);
if (ExposePublicDeclsInClangHeader ||
M->DeclContext::getASTContext().LangOpts.EnableCXXInterop) {
os << getModuleContentsCxxString(
*M, interopContext,
/*requiresExposedAttribute=*/!ExposePublicDeclsInClangHeader);
}
});
writeEpilogue(os);
Expand Down
8 changes: 5 additions & 3 deletions lib/PrintAsClang/PrintClangFunction.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include "swift/AST/Decl.h"
#include "swift/AST/GenericParamList.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/SwiftNameTranslation.h"
#include "swift/AST/Type.h"
#include "swift/AST/TypeVisitor.h"
#include "swift/ClangImporter/ClangImporter.h"
Expand Down Expand Up @@ -701,8 +702,8 @@ void DeclAndTypeClangFunctionPrinter::printCxxMethod(
modifiers.isConst =
!isa<ClassDecl>(typeDeclContext) && !isMutating && !isConstructor;
printFunctionSignature(
FD, isConstructor ? "init" : FD->getName().getBaseIdentifier().get(),
resultTy, FunctionSignatureKind::CxxInlineThunk, {}, modifiers);
FD, isConstructor ? "init" : cxx_translation::getNameForCxx(FD), resultTy,
FunctionSignatureKind::CxxInlineThunk, {}, modifiers);
if (!isDefinition) {
os << ";\n";
return;
Expand Down Expand Up @@ -734,7 +735,8 @@ static bool canRemapBoolPropertyNameDirectly(StringRef name) {
static std::string remapPropertyName(const AccessorDecl *accessor,
Type resultTy) {
// For a getter or setter, go through the variable or subscript decl.
StringRef propertyName = accessor->getStorage()->getBaseIdentifier().str();
StringRef propertyName =
cxx_translation::getNameForCxx(accessor->getStorage());

// Boolean property getters can be remapped directly in certain cases.
if (accessor->isGetter() && resultTy->isBool() &&
Expand Down
Loading