Skip to content

Make @objcImpl work with @_cdecl #69468

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 10 commits into from
Dec 14, 2023
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 include/swift/AST/Attr.def
Original file line number Diff line number Diff line change
Expand Up @@ -246,7 +246,7 @@ DECL_ATTR(_restatedObjCConformance, RestatedObjCConformance,
OnProtocol | UserInaccessible | LongAttribute | RejectByParser | NotSerialized | ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
70)
DECL_ATTR(_objcImplementation, ObjCImplementation,
OnExtension | UserInaccessible | ABIBreakingToAdd | ABIBreakingToRemove | APIBreakingToAdd | APIBreakingToRemove,
OnExtension | OnAbstractFunction | UserInaccessible | ABIBreakingToAdd | ABIBreakingToRemove | APIBreakingToAdd | APIBreakingToRemove,
72)
DECL_ATTR(_optimize, Optimize,
OnAbstractFunction | OnSubscript | OnVar | UserInaccessible | ABIStableToAdd | ABIStableToRemove | APIStableToAdd | APIStableToRemove,
Expand Down
14 changes: 9 additions & 5 deletions include/swift/AST/Decl.h
Original file line number Diff line number Diff line change
Expand Up @@ -941,6 +941,11 @@ class alignas(1 << DeclAlignInBits) Decl : public ASTAllocated<Decl> {
/// attribute macro expansion.
DeclAttributes getSemanticAttrs() const;

/// True if this declaration provides an implementation for an imported
/// Objective-C declaration. This implies various restrictions and special
/// behaviors for it and, if it's an extension, its members.
bool isObjCImplementation() const;

using AuxiliaryDeclCallback = llvm::function_ref<void(Decl *)>;

/// Iterate over the auxiliary declarations for this declaration,
Expand Down Expand Up @@ -1836,11 +1841,6 @@ class ExtensionDecl final : public GenericContext, public Decl,
/// resiliently moved into the original protocol itself.
bool isEquivalentToExtendedContext() const;

/// True if this extension provides an implementation for an imported
/// Objective-C \c \@interface. This implies various restrictions and special
/// behaviors for its members.
bool isObjCImplementation() const;

/// Returns the name of the category specified by the \c \@_objcImplementation
/// attribute, or \c None if the name is invalid. Do not call unless
/// \c isObjCImplementation() returns \c true.
Expand Down Expand Up @@ -2778,6 +2778,10 @@ class ValueDecl : public Decl {
return DeclNameRef(Name);
}

/// Retrieve the C declaration name that names this function, or empty
/// string if it has none.
StringRef getCDeclName() const;

/// Retrieve the name to use for this declaration when interoperating
/// with the Objective-C runtime.
///
Expand Down
5 changes: 3 additions & 2 deletions include/swift/AST/DiagnosticsClangImporter.def
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,9 @@ WARNING(api_pattern_attr_ignored, none,

ERROR(objc_implementation_two_impls, none,
"duplicate implementation of Objective-C %select{|category %0 on }0"
"class %1",
(Identifier, ValueDecl *))
"%kind1",
(Identifier, Decl *))

NOTE(previous_objc_implementation, none,
"previously implemented by extension here", ())

Expand Down
8 changes: 8 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -1740,9 +1740,17 @@ ERROR(attr_objc_implementation_category_not_found,none,
"could not find category %0 on Objective-C class %1; make sure your "
"umbrella or bridging header imports the header that declares it",
(Identifier, ValueDecl*))
ERROR(attr_objc_implementation_func_not_found,none,
"could not find imported function '%0' matching %kind1; make sure your "
"umbrella or bridging header imports the header that declares it",
(StringRef, ValueDecl*))
NOTE(attr_objc_implementation_fixit_remove_category_name,none,
"remove arguments to implement the main '@interface' for this class",
())
ERROR(attr_objc_implementation_no_category_for_func,none,
"%kind0 does not belong to an Objective-C category; remove the category "
"name from this attribute",
(ValueDecl*))
ERROR(attr_objc_implementation_no_conformance,none,
"'@_objcImplementation' extension cannot add conformance to %0; "
"add this conformance %select{with an ordinary extension|"
Expand Down
3 changes: 2 additions & 1 deletion include/swift/AST/LookupKinds.h
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,8 @@ enum NLOptions : unsigned {

/// Don't check access when doing lookup into a type.
///
/// This option is not valid when performing lookup into a module.
/// When performing lookup into a module, this option only applies to
/// declarations in the same module the lookup is coming from.
NL_IgnoreAccessControl = 1 << 3,

/// This lookup should only return type declarations.
Expand Down
4 changes: 2 additions & 2 deletions include/swift/AST/TypeCheckRequests.h
Original file line number Diff line number Diff line change
Expand Up @@ -4544,7 +4544,7 @@ class SemanticBriefCommentRequest
/// This is done on all of a class's implementations at once to improve diagnostics.
class TypeCheckObjCImplementationRequest
: public SimpleRequest<TypeCheckObjCImplementationRequest,
evaluator::SideEffect(ExtensionDecl *),
evaluator::SideEffect(Decl *),
RequestFlags::Cached> {
public:
using SimpleRequest::SimpleRequest;
Expand All @@ -4554,7 +4554,7 @@ class TypeCheckObjCImplementationRequest

// Evaluation.
evaluator::SideEffect
evaluate(Evaluator &evaluator, ExtensionDecl *ED) const;
evaluate(Evaluator &evaluator, Decl *D) const;

public:
// Separate caching.
Expand Down
21 changes: 19 additions & 2 deletions lib/AST/Decl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1847,7 +1847,7 @@ Type ExtensionDecl::getExtendedType() const {
return ErrorType::get(ctx);
}

bool ExtensionDecl::isObjCImplementation() const {
bool Decl::isObjCImplementation() const {
return getAttrs().hasAttribute<ObjCImplementationAttr>(/*AllowInvalid=*/true);
}

Expand Down Expand Up @@ -3869,6 +3869,22 @@ void ValueDecl::setInterfaceType(Type type) {
std::move(type));
}

StringRef ValueDecl::getCDeclName() const {
// Treat imported C functions as implicitly @_cdecl.
if (auto clangDecl = dyn_cast_or_null<clang::FunctionDecl>(getClangDecl())) {
if (clangDecl->getLanguageLinkage() == clang::CLanguageLinkage
&& clangDecl->getIdentifier())
return clangDecl->getName();
}

// Handle explicit cdecl attributes.
if (auto cdeclAttr = getAttrs().getAttribute<CDeclAttr>()) {
return cdeclAttr->Name;
}

return "";
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's also @extern(c, "name"), IIRC

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It looks like @_extern requires the function to not have a body, so it wouldn't make sense to use it with @implementation (which provides a body). Is that changing?

}

llvm::Optional<ObjCSelector>
ValueDecl::getObjCRuntimeName(bool skipIsObjCResolution) const {
if (auto func = dyn_cast<AbstractFunctionDecl>(this))
Expand Down Expand Up @@ -4404,7 +4420,8 @@ static bool checkAccess(const DeclContext *useDC, const ValueDecl *VD,
// a context where we would access its storage directly, forbid access. Name
// lookups will instead find and use the matching interface decl.
// FIXME: Passing `true` for `isAccessOnSelf` may cause false positives.
if (isObjCMemberImplementation(VD, getAccessLevel) &&
if ((VD->isObjCImplementation() ||
isObjCMemberImplementation(VD, getAccessLevel)) &&
VD->getAccessSemanticsFromContext(useDC, /*isAccessOnSelf=*/true)
!= AccessSemantics::DirectToStorage)
return false;
Expand Down
5 changes: 5 additions & 0 deletions lib/AST/ModuleNameLookup.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,11 @@ void ModuleNameLookup<LookupStrategy>::lookupInModule(
if (resolutionKind == ResolutionKind::MacrosOnly && !isa<MacroDecl>(VD))
return true;
if (respectAccessControl &&
// NL_IgnoreAccessControl applies only to the current module.
!((options & NL_IgnoreAccessControl) &&
moduleScopeContext &&
moduleScopeContext->getParentModule() ==
VD->getDeclContext()->getParentModule()) &&
!VD->isAccessibleFrom(moduleScopeContext, false,
includeUsableFromInline))
return true;
Expand Down
2 changes: 1 addition & 1 deletion lib/AST/SwiftNameTranslation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -139,7 +139,7 @@ getObjCNameForSwiftDecl(const ValueDecl *VD, DeclName PreferredName){
bool swift::objc_translation::
isVisibleToObjC(const ValueDecl *VD, AccessLevel minRequiredAccess,
bool checkParent) {
if (!(VD->isObjC() || VD->getAttrs().hasAttribute<CDeclAttr>()))
if (!(VD->isObjC() || !VD->getCDeclName().empty()))
return false;
if (VD->getFormalAccess() >= minRequiredAccess) {
return true;
Expand Down
135 changes: 104 additions & 31 deletions lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5827,21 +5827,6 @@ findImplsGivenInterface(ClassDecl *classDecl, Identifier categoryName) {
impls.push_back(ext);
}

if (impls.size() > 1) {
llvm::sort(impls, OrderDecls());

auto &diags = classDecl->getASTContext().Diags;
for (auto extraImpl : llvm::ArrayRef<Decl *>(impls).drop_front()) {
auto attr = extraImpl->getAttrs().getAttribute<ObjCImplementationAttr>();
attr->setCategoryNameInvalid();

diags.diagnose(attr->getLocation(), diag::objc_implementation_two_impls,
categoryName, classDecl)
.fixItRemove(attr->getRangeWithAt());
diags.diagnose(impls.front(), diag::previous_objc_implementation);
}
}

return impls;
}

Expand Down Expand Up @@ -5872,10 +5857,26 @@ findInterfaceGivenImpl(ClassDecl *classDecl, ExtensionDecl *ext) {
}

static ObjCInterfaceAndImplementation
constructResult(Decl *interface, llvm::TinyPtrVector<Decl *> impls) {
if (impls.empty())
constructResult(Decl *interface, llvm::TinyPtrVector<Decl *> &impls,
Decl *diagnoseOn, Identifier categoryName) {
if (!interface || impls.empty())
return ObjCInterfaceAndImplementation();

if (impls.size() > 1) {
llvm::sort(impls, OrderDecls());

auto &diags = interface->getASTContext().Diags;
for (auto extraImpl : llvm::ArrayRef<Decl *>(impls).drop_front()) {
auto attr = extraImpl->getAttrs().getAttribute<ObjCImplementationAttr>();
attr->setCategoryNameInvalid();

diags.diagnose(attr->getLocation(), diag::objc_implementation_two_impls,
categoryName, diagnoseOn)
.fixItRemove(attr->getRangeWithAt());
diags.diagnose(impls.front(), diag::previous_objc_implementation);
}
}

return ObjCInterfaceAndImplementation(interface, impls.front());
}

Expand Down Expand Up @@ -5924,31 +5925,103 @@ findContextInterfaceAndImplementation(DeclContext *dc) {
// look for extensions implementing it.

auto implDecls = findImplsGivenInterface(classDecl, categoryName);
return constructResult(interfaceDecl, implDecls);
return constructResult(interfaceDecl, implDecls, classDecl, categoryName);
}

static void lookupRelatedFuncs(AbstractFunctionDecl *func,
SmallVectorImpl<ValueDecl *> &results) {
DeclName swiftName;
if (auto accessor = dyn_cast<AccessorDecl>(func))
swiftName = accessor->getStorage()->getName();
else
swiftName = func->getName();

if (auto ty = func->getDeclContext()->getSelfNominalTypeDecl()) {
ty->lookupQualified({ ty }, DeclNameRef(swiftName), func->getLoc(),
NL_QualifiedDefault | NL_IgnoreAccessControl, results);
}
else {
auto mod = func->getDeclContext()->getParentModule();
mod->lookupQualified(mod, DeclNameRef(swiftName), func->getLoc(),
NL_RemoveOverridden | NL_IgnoreAccessControl, results);
}
}

static ObjCInterfaceAndImplementation
findFunctionInterfaceAndImplementation(AbstractFunctionDecl *func) {
if (!func)
return {};

// If this isn't either a clang import or an implementation, there's no point
// doing any work here.
if (!func->hasClangNode() && !func->isObjCImplementation())
return {};

OptionalEnum<AccessorKind> accessorKind;
if (auto accessor = dyn_cast<AccessorDecl>(func))
accessorKind = accessor->getAccessorKind();

StringRef clangName = func->getCDeclName();
if (clangName.empty())
return {};

SmallVector<ValueDecl *, 4> results;
lookupRelatedFuncs(func, results);

// Classify the `results` as either the interface or an implementation.
// (Multiple implementations are invalid but utterable.)
Decl *interface = nullptr;
TinyPtrVector<Decl *> impls;

for (ValueDecl *result : results) {
AbstractFunctionDecl *resultFunc = nullptr;
if (accessorKind) {
if (auto resultStorage = dyn_cast<AbstractStorageDecl>(result))
resultFunc = resultStorage->getAccessor(*accessorKind);
}
else
resultFunc = dyn_cast<AbstractFunctionDecl>(result);

if (!resultFunc)
continue;

if (resultFunc->getCDeclName() != clangName)
continue;

if (resultFunc->hasClangNode()) {
if (interface) {
// This clang name is overloaded. That should only happen with C++
// functions/methods, which aren't currently supported.
return {};
}
interface = result;
} else if (resultFunc->isObjCImplementation()) {
impls.push_back(result);
}
}

// If we found enough decls to construct a result, `func` should be among them
// somewhere.
assert(interface == nullptr || impls.empty() ||
interface == func || llvm::is_contained(impls, func));

return constructResult(interface, impls, interface,
/*categoryName=*/Identifier());
}

ObjCInterfaceAndImplementation ObjCInterfaceAndImplementationRequest::
evaluate(Evaluator &evaluator, Decl *decl) const {
// These have direct links to their counterparts through the
// Types and extensions have direct links to their counterparts through the
// `@_objcImplementation` attribute. Let's resolve that.
// (Also directing nulls here, where they'll early-return.)
if (auto ty = dyn_cast_or_null<NominalTypeDecl>(decl))
return findContextInterfaceAndImplementation(ty);
else if (auto ext = dyn_cast<ExtensionDecl>(decl))
return findContextInterfaceAndImplementation(ext);
// Abstract functions have to be matched through their @_cdecl attributes.
else if (auto func = dyn_cast<AbstractFunctionDecl>(decl))
return findFunctionInterfaceAndImplementation(func);

// Anything else is resolved by first locating the context's interface and
// impl, then matching it to its counterpart. (Instead of calling
// `findContextInterfaceAndImplementation()` directly, we'll use the request
// recursively to take advantage of caching.)
auto contextDecl = decl->getDeclContext()->getAsDecl();
if (!contextDecl)
return {};

ObjCInterfaceAndImplementationRequest req(contextDecl);
/*auto contextPair =*/ evaluateOrDefault(evaluator, req, {});

// TODO: Implement member matching.
return {};
}

Expand Down
5 changes: 4 additions & 1 deletion lib/IRGen/GenDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -3544,7 +3544,10 @@ llvm::Function *IRGenModule::getAddrOfSILFunction(
if (hasOrderNumber) {
auto &fnList = Module.getFunctionList();
fnList.remove(fn);
fnList.insert(llvm::Module::iterator(insertBefore), fn);
if (insertBefore)
fnList.insert(llvm::Module::iterator(insertBefore), fn);
else
fnList.push_back(fn);

EmittedFunctionsByOrder.insert(orderNumber, fn);
}
Expand Down
17 changes: 10 additions & 7 deletions lib/PrintAsClang/DeclAndTypePrinter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1414,8 +1414,7 @@ class DeclAndTypePrinter::Implementation

assert(FD->getAttrs().hasAttribute<CDeclAttr>() && "not a cdecl function");
os << "SWIFT_EXTERN ";
printFunctionDeclAsCFunctionDecl(
FD, FD->getAttrs().getAttribute<CDeclAttr>()->Name, resultTy);
printFunctionDeclAsCFunctionDecl(FD, FD->getCDeclName(), resultTy);
printFunctionClangAttributes(FD, funcTy);
printAvailability(FD);
os << ";\n";
Expand All @@ -1425,12 +1424,12 @@ class DeclAndTypePrinter::Implementation
FunctionSwiftABIInformation(AbstractFunctionDecl *FD,
LoweredFunctionSignature signature)
: signature(signature) {
isCDecl = FD->getAttrs().hasAttribute<CDeclAttr>();
isCDecl = !FD->getCDeclName().empty();
if (!isCDecl) {
auto mangledName = SILDeclRef(FD).mangle();
symbolName = FD->getASTContext().AllocateCopy(mangledName);
} else {
symbolName = FD->getAttrs().getAttribute<CDeclAttr>()->Name;
symbolName = FD->getCDeclName();
}
}

Expand Down Expand Up @@ -2858,12 +2857,16 @@ static bool hasExposeAttr(const ValueDecl *VD, bool isExtension = false) {
return false;
}

/// Skip \c \@objcImplementation \c extension member implementations and
/// overrides. They are already declared in handwritten headers, and they may
/// have attributes that aren't allowed in a category.
/// Skip \c \@objcImplementation functions, \c extension member
/// implementations, and overrides. They are already declared in handwritten
/// headers, and they may have attributes that aren't allowed in a category.
///
/// \return true if \p VD should \em not be included in the header.
static bool excludeForObjCImplementation(const ValueDecl *VD) {
// If it's an ObjC implementation (and not an extension, which might have
// members that need printing), skip it; it's declared elsewhere.
if (VD->isObjCImplementation() && ! isa<ExtensionDecl>(VD))
return true;
// Exclude member implementations; they are declared elsewhere.
if (VD->isObjCMemberImplementation())
return true;
Expand Down
Loading