Skip to content

🍒[cxx-interop] Add std::set initializer that takes a Swift Sequence #66600

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 3 commits into from
Jul 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
42 changes: 41 additions & 1 deletion lib/ClangImporter/ClangDerivedConformances.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -565,6 +565,23 @@ void swift::conformToCxxSequenceIfNeeded(
}
}

static bool isStdSetType(const clang::CXXRecordDecl *clangDecl) {
return isStdDecl(clangDecl, {"set", "unordered_set", "multiset"});
}

bool swift::isUnsafeStdMethod(const clang::CXXMethodDecl *methodDecl) {
auto parentDecl =
dyn_cast<clang::CXXRecordDecl>(methodDecl->getDeclContext());
if (!parentDecl)
return false;
if (!isStdSetType(parentDecl))
return false;
if (methodDecl->getDeclName().isIdentifier() &&
methodDecl->getName() == "insert")
return true;
return false;
}

void swift::conformToCxxSetIfNeeded(ClangImporter::Implementation &impl,
NominalTypeDecl *decl,
const clang::CXXRecordDecl *clangDecl) {
Expand All @@ -576,7 +593,7 @@ void swift::conformToCxxSetIfNeeded(ClangImporter::Implementation &impl,

// Only auto-conform types from the C++ standard library. Custom user types
// might have a similar interface but different semantics.
if (!isStdDecl(clangDecl, {"set", "unordered_set", "multiset"}))
if (!isStdSetType(clangDecl))
return;

auto valueType = lookupDirectSingleWithoutExtensions<TypeAliasDecl>(
Expand All @@ -586,10 +603,33 @@ void swift::conformToCxxSetIfNeeded(ClangImporter::Implementation &impl,
if (!valueType || !sizeType)
return;

auto insertId = ctx.getIdentifier("__insertUnsafe");
auto inserts = lookupDirectWithoutExtensions(decl, insertId);
FuncDecl *insert = nullptr;
for (auto candidate : inserts) {
if (auto candidateMethod = dyn_cast<FuncDecl>(candidate)) {
if (!candidateMethod->hasParameterList())
continue;
auto params = candidateMethod->getParameters();
if (params->size() != 1)
continue;
auto param = params->front();
if (param->getType()->getCanonicalType() !=
valueType->getUnderlyingType()->getCanonicalType())
continue;
insert = candidateMethod;
break;
}
}
if (!insert)
return;

impl.addSynthesizedTypealias(decl, ctx.Id_Element,
valueType->getUnderlyingType());
impl.addSynthesizedTypealias(decl, ctx.getIdentifier("Size"),
sizeType->getUnderlyingType());
impl.addSynthesizedTypealias(decl, ctx.getIdentifier("InsertionResult"),
insert->getResultInterfaceType());
impl.addSynthesizedProtocolAttrs(decl, {KnownProtocolKind::CxxSet});
}

Expand Down
2 changes: 2 additions & 0 deletions lib/ClangImporter/ClangDerivedConformances.h
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ namespace swift {

bool isIterator(const clang::CXXRecordDecl *clangDecl);

bool isUnsafeStdMethod(const clang::CXXMethodDecl *methodDecl);

/// If the decl is a C++ input iterator, synthesize a conformance to the
/// UnsafeCxxInputIterator protocol, which is defined in the Cxx module.
void conformToCxxIteratorIfNeeded(ClangImporter::Implementation &impl,
Expand Down
5 changes: 5 additions & 0 deletions lib/ClangImporter/ClangImporter.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6747,6 +6747,11 @@ bool IsSafeUseOfCxxDecl::evaluate(Evaluator &evaluator,
method->getReturnType()->isReferenceType())
return false;

// Check if it's one of the known unsafe methods we currently
// mark as safe by default.
if (isUnsafeStdMethod(method))
return false;

// Try to figure out the semantics of the return type. If it's a
// pointer/iterator, it's unsafe.
if (auto returnType = dyn_cast<clang::RecordType>(
Expand Down
20 changes: 20 additions & 0 deletions stdlib/public/Cxx/CxxSet.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,31 @@
public protocol CxxSet<Element> {
associatedtype Element
associatedtype Size: BinaryInteger
associatedtype InsertionResult // std::pair<iterator, bool>

init()

@discardableResult
mutating func __insertUnsafe(_ element: Element) -> InsertionResult

func count(_ element: Element) -> Size
}

extension CxxSet {
/// Creates a C++ set containing the elements of a Swift Sequence.
///
/// This initializes the set by copying every element of the sequence.
///
/// - Complexity: O(*n*), where *n* is the number of elements in the Swift
/// sequence
@inlinable
public init<S: Sequence>(_ sequence: __shared S) where S.Element == Element {
self.init()
for item in sequence {
self.__insertUnsafe(item)
}
}

@inlinable
public func contains(_ element: Element) -> Bool {
return count(element) > 0
Expand Down
14 changes: 14 additions & 0 deletions test/Interop/Cxx/stdlib/use-std-set.swift
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,18 @@ StdSetTestSuite.test("MultisetOfCInt.contains") {
expectFalse(s.contains(3))
}

StdSetTestSuite.test("SetOfCInt.init()") {
let s = SetOfCInt([1, 3, 5])
expectTrue(s.contains(1))
expectFalse(s.contains(2))
expectTrue(s.contains(3))
}

StdSetTestSuite.test("UnorderedSetOfCInt.init()") {
let s = UnorderedSetOfCInt([1, 3, 5])
expectTrue(s.contains(1))
expectFalse(s.contains(2))
expectTrue(s.contains(3))
}

runAllTests()