Skip to content

[cxx-interop] Add CxxOptional protocol for std::optional ergonomics #63683

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 2 commits into from
Mar 6, 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
1 change: 1 addition & 0 deletions include/swift/AST/KnownProtocols.def
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ PROTOCOL(DistributedTargetInvocationResultHandler)
// C++ Standard Library Overlay:
PROTOCOL(CxxConvertibleToCollection)
PROTOCOL(CxxDictionary)
PROTOCOL(CxxOptional)
PROTOCOL(CxxPair)
PROTOCOL(CxxSet)
PROTOCOL(CxxRandomAccessCollection)
Expand Down
1 change: 1 addition & 0 deletions lib/AST/ASTContext.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1127,6 +1127,7 @@ ProtocolDecl *ASTContext::getProtocol(KnownProtocolKind kind) const {
case KnownProtocolKind::CxxConvertibleToCollection:
case KnownProtocolKind::CxxDictionary:
case KnownProtocolKind::CxxPair:
case KnownProtocolKind::CxxOptional:
case KnownProtocolKind::CxxRandomAccessCollection:
case KnownProtocolKind::CxxSet:
case KnownProtocolKind::CxxSequence:
Expand Down
52 changes: 42 additions & 10 deletions lib/ClangImporter/ClangDerivedConformances.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,16 @@ static bool isConcreteAndValid(ProtocolConformanceRef conformanceRef,
});
}

static bool isStdDecl(const clang::CXXRecordDecl *clangDecl,
llvm::ArrayRef<StringRef> names) {
if (!clangDecl->isInStdNamespace())
return false;
if (!clangDecl->getIdentifier())
return false;
StringRef name = clangDecl->getName();
return llvm::is_contained(names, name);
}

static clang::TypeDecl *
getIteratorCategoryDecl(const clang::CXXRecordDecl *clangDecl) {
clang::IdentifierInfo *iteratorCategoryDeclName =
Expand Down Expand Up @@ -380,6 +390,38 @@ void swift::conformToCxxIteratorIfNeeded(
decl, {KnownProtocolKind::UnsafeCxxRandomAccessIterator});
}

void swift::conformToCxxOptionalIfNeeded(
ClangImporter::Implementation &impl, NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl) {
PrettyStackTraceDecl trace("conforming to CxxOptional", decl);

assert(decl);
assert(clangDecl);
ASTContext &ctx = decl->getASTContext();

if (!isStdDecl(clangDecl, {"optional"}))
return;

ProtocolDecl *cxxOptionalProto =
ctx.getProtocol(KnownProtocolKind::CxxOptional);
// If the Cxx module is missing, or does not include one of the necessary
// protocol, bail.
if (!cxxOptionalProto)
return;

auto pointeeId = ctx.getIdentifier("pointee");
auto pointees = lookupDirectWithoutExtensions(decl, pointeeId);
if (pointees.size() != 1)
return;
auto pointee = dyn_cast<VarDecl>(pointees.front());
if (!pointee)
return;
auto pointeeTy = pointee->getInterfaceType();

impl.addSynthesizedTypealias(decl, ctx.getIdentifier("Wrapped"), pointeeTy);
impl.addSynthesizedProtocolAttrs(decl, {KnownProtocolKind::CxxOptional});
}

void swift::conformToCxxSequenceIfNeeded(
ClangImporter::Implementation &impl, NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl) {
Expand Down Expand Up @@ -522,16 +564,6 @@ void swift::conformToCxxSequenceIfNeeded(
}
}

static bool isStdDecl(const clang::CXXRecordDecl *clangDecl,
llvm::ArrayRef<StringRef> names) {
if (!clangDecl->isInStdNamespace())
return false;
if (!clangDecl->getIdentifier())
return false;
StringRef name = clangDecl->getName();
return llvm::is_contained(names, name);
}

void swift::conformToCxxSetIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl) {
Expand Down
6 changes: 6 additions & 0 deletions lib/ClangImporter/ClangDerivedConformances.h
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,12 @@ void conformToCxxIteratorIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl);

/// If the decl is an instantiation of C++ `std::optional`, synthesize a
/// conformance to CxxOptional protocol, which is defined in the Cxx module.
void conformToCxxOptionalIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl);

/// If the decl is a C++ sequence, synthesize a conformance to the CxxSequence
/// protocol, which is defined in the Cxx module.
void conformToCxxSequenceIfNeeded(ClangImporter::Implementation &impl,
Expand Down
1 change: 1 addition & 0 deletions lib/ClangImporter/ImportDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2633,6 +2633,7 @@ namespace {
conformToCxxSetIfNeeded(Impl, nominalDecl, decl);
conformToCxxDictionaryIfNeeded(Impl, nominalDecl, decl);
conformToCxxPairIfNeeded(Impl, nominalDecl, decl);
conformToCxxOptionalIfNeeded(Impl, nominalDecl, decl);
}

if (auto *ntd = dyn_cast<NominalTypeDecl>(result))
Expand Down
18 changes: 17 additions & 1 deletion lib/ClangImporter/ImportName.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,9 @@ static bool isErrorOutParameter(const clang::ParmVarDecl *param,

static bool isBoolType(clang::ASTContext &ctx, clang::QualType type) {
do {
if (type->isBooleanType())
return true;

// Check whether we have a typedef for "BOOL" or "Boolean".
if (auto typedefType = dyn_cast<clang::TypedefType>(type.getTypePtr())) {
auto typedefDecl = typedefType->getDecl();
Expand Down Expand Up @@ -1845,7 +1848,20 @@ ImportedName NameImporter::importNameImpl(const clang::NamedDecl *D,
break;
}

case clang::DeclarationName::CXXConversionFunctionName:
case clang::DeclarationName::CXXConversionFunctionName: {
auto conversionDecl = dyn_cast<clang::CXXConversionDecl>(D);
if (!conversionDecl)
return ImportedName();
auto toType = conversionDecl->getConversionType();
// Only import `operator bool()` for now.
if (isBoolType(clangSema.Context, toType)) {
isFunction = true;
baseName = "__convertToBool";
addEmptyArgNamesForClangFunction(conversionDecl, argumentNames);
break;
}
return ImportedName();
}
case clang::DeclarationName::CXXDestructorName:
case clang::DeclarationName::CXXLiteralOperatorName:
case clang::DeclarationName::CXXUsingDirective:
Expand Down
1 change: 1 addition & 0 deletions lib/IRGen/GenMeta.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5877,6 +5877,7 @@ SpecialProtocol irgen::getSpecialProtocolID(ProtocolDecl *P) {
case KnownProtocolKind::CxxConvertibleToCollection:
case KnownProtocolKind::CxxDictionary:
case KnownProtocolKind::CxxPair:
case KnownProtocolKind::CxxOptional:
case KnownProtocolKind::CxxRandomAccessCollection:
case KnownProtocolKind::CxxSet:
case KnownProtocolKind::CxxSequence:
Expand Down
1 change: 1 addition & 0 deletions stdlib/public/Cxx/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ add_swift_target_library(swiftCxx ${SWIFT_CXX_LIBRARY_KIND} NO_LINK_NAME IS_STDL
CxxConvertibleToCollection.swift
CxxDictionary.swift
CxxPair.swift
CxxOptional.swift
CxxSet.swift
CxxRandomAccessCollection.swift
CxxSequence.swift
Expand Down
46 changes: 46 additions & 0 deletions stdlib/public/Cxx/CxxOptional.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

public protocol CxxOptional<Wrapped> {
associatedtype Wrapped

func __convertToBool() -> Bool

var pointee: Wrapped { get }
}

extension CxxOptional {
@inlinable
public var hasValue: Bool {
Copy link
Contributor Author

Choose a reason for hiding this comment

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

This property provides the only way to check if the std::optional has a value from Swift.

get {
return __convertToBool()
}
}

@inlinable
public var value: Wrapped {
get {
return pointee
}
}
}

extension Optional {
@inlinable
public init(fromCxx value: some CxxOptional<Wrapped>) {
guard value.__convertToBool() else {
self = nil
return
}
self = value.pointee
}
}
3 changes: 3 additions & 0 deletions test/Interop/Cxx/operators/Inputs/member-inline.h
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@ struct LoadableIntWrapper {
return value + x * y;
}

operator int() const { return value; }

LoadableIntWrapper &operator++() {
value++;
return *this;
Expand All @@ -48,6 +50,7 @@ struct LoadableBoolWrapper {
LoadableBoolWrapper operator!() {
return LoadableBoolWrapper{.value = !value};
}
operator bool() const { return value; }
};

template<class T>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

// CHECK: struct LoadableBoolWrapper {
// CHECK: prefix static func ! (lhs: inout LoadableBoolWrapper) -> LoadableBoolWrapper
// CHECK: func __convertToBool() -> Bool
// CHECK: }

// CHECK: struct AddressOnlyIntWrapper {
Expand Down
22 changes: 21 additions & 1 deletion test/Interop/Cxx/stdlib/use-std-optional.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop -Xcc -std=c++17)
// RUN: %target-run-simple-swift(-I %S/Inputs -Xfrontend -enable-experimental-cxx-interop -Xcc -std=c++17 -Xfrontend -validate-tbd-against-ir=none)
//
// REQUIRES: executable_test
// REQUIRES: OS=macosx
Expand All @@ -15,4 +15,24 @@ StdOptionalTestSuite.test("pointee") {
expectEqual(123, pointee)
}

StdOptionalTestSuite.test("std::optional => Swift.Optional") {
let nonNilOpt = getNonNilOptional()
let swiftOptional = Optional(fromCxx: nonNilOpt)
expectNotNil(swiftOptional)
expectEqual(123, swiftOptional!)

let nilOpt = getNilOptional()
let swiftNil = Optional(fromCxx: nilOpt)
expectNil(swiftNil)
}

StdOptionalTestSuite.test("std::optional hasValue/value") {
let nonNilOpt = getNonNilOptional()
expectTrue(nonNilOpt.hasValue)
expectEqual(123, nonNilOpt.value)

let nilOpt = getNilOptional()
expectFalse(nilOpt.hasValue)
}

runAllTests()